为什么jQuery.fn.init()
方法中的this
是一个类数组对象,而不是指向的jQuery.fn
?
测试方法:
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
console.log(this); // this是个空的类数组对象,这是为什么?
return this;
}
执行$(null)
.
那是因为:jQuery对象本身就是个类数组对象
返回的this
就是jQuery.fn
的实例啊,注意看:
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
当你使用$()
之后,实际是调用了new jQuery.fn.init( selector, context )
。
现在对于打印出"对象"应该没有异议了吧?
然后再来看为什么是一个空的类数组对象,看这里:
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
......
这是jQuery.fn
的类声明体,看到了么,好多数组才有的属性哦!!!
祝你玩的愉快
因为类数组的length
是0.