为什么$(selector)之后,返回的是jQuery对象?

来源:互联网 发布:企业沟通软件 编辑:程序博客网 时间:2024/06/06 01:54

1)为什么$(selector)之后,返回的是jQuery对象?

答:从jQuery的源代码中,我们可以知道:var $ = jQuery.因此当我们$(selector)操作时,其实就是jQuery(selector),创建的是一个jQuery对象.当然正确的写法应该是这样的:var jq = new $(selector);而jQuery使用了一个小技巧在外部避免了new,在jquery方法内部:jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},

2) 问:为什么创建一个jQuery对象之后,我们可以这样写$(selector).each(function(index){…});进行遍历操作呢?

答:其实jQuery(selector)方法调用时,在jQuery(selector)方法内部,最后返回的是一个数组:return this.setArray(a);而each方法体内部是一个for循环,在循环体内是这样调用的:method.call(this[i],i).

3) 问:为什么jQuery能做到jQuery对象属性/方法/事件的插件式扩展?

答:如果您有一些javasciprt的面向对象方面的知识,就会知道,jQuery.prototype原型对象上的扩展属性/方法和事件,将会给jQuery的对象\”扩展”.基于这一点,jQuery是这样写的:jQuery.fn = jQuery.prototype.所以,当我们扩展一个插件功能时,如下:

jQuery.fn.check = function() {

return this.each(function() {

this.checked = true;

});

};

其实就是:

jQuery.prototype.check = function() {

return this.each(function() {

this.checked = true;

});

};


0 0