jquery对外暴露了两个方法:jQuery和$,
* 这两方法实际上是同一个方法,
* 通过调用这两个方法,可以得到一个jQuery实例对象。
* jQuery实例对象是一个伪数组对象。
* jQuery和$实际上是一个工厂函数。
先实现一个弹出框插件的实列:(为了实现插件机制,让外界可以透过jQuery.fn扩充方法。)
<script>
/*
* jQuery插件实现机制:
* 就是给原型添加一些功能方法。
* */
(function( w ) {
// 对外暴露的工厂函数
function jQuery() {
return new jQuery.fn.init();
}
// 给原型提供一个简写方式
jQuery.fn = jQuery.prototype = {
};
// init是jQuery中真正的构造函数
var init = jQuery.fn.init = function() {
};
// 替换构造函数的原型 为 jQuery工厂的原型
init.prototype = jQuery.fn;
// 把工厂通过两个变量暴露出去
w.jQuery = w.$ = jQuery;
}( window ));
// 实现一个jQ弹出框插件
jQuery.fn.alert = function( msg ) {
alert( msg );
};
// 测试插件
var $$ = $();
$$.alert('弹出框插件');
</script>
Object.prototype.toString:
作用:根据内部的this返回一个类似于这样的字符串'[object constructorName]'
这个方法有个缺点,不能获取用户自定义对象的具体类型,只能获取内置对象的类型。
//测试
console.log(Object.prototype.toString.call([]));
console.log(Object.prototype.toString.call( new Date() ));
console.log(Object.prototype.toString.call( Array ));
console.log(Object.prototype.toString.call( Date ));
简写 ==> 因为{}对象直接继承Object.prototype,
所以通过这个对象得到的toString,一定来自Object.prototype。
console.log(({}).toString.call([]));
console.log(({}).toString.call( new Date() ));
console.log(({}).toString.call( Array ));
console.log(({}).toString.call( Date ));
用这个toString获取自定义对象的类型
function Person(){}
var xiaofang = new Person();
console.log(({}).toString.call( xiaofang ));
代码块就是一对大括号。
{
var a = 1;
console.log(a);
}
{}.toString();//错误
console.log(({}).toString());