jQuery对象包含的内容及两种扩展方式
标识符jQuery,我们可以理解其为一个function,
而jQuery的fn,我们理解其为prototype,因为jQuery.fn = jQuery.prototype =
还要注意一句话jQuery.fn.init.prototype = jQuery.fn。该句把function jQuery的原型赋值给了function init的原型。
当调用$("#id")时返回的对象组成包括两个部分,由function init中this带的(如this.context);由function jQuery的prototype带的(如this.size/this.toArray);
jQuery对象由以下部分组成:
1,挂在jQuery.prototype.init中的this上的属性或方法。
2,挂在jQuery.prototype.init.prototype上的属性或方法。
3,因为把jQuery.prototype赋值给了jQuery.prototype.init.prototype,所以挂在jQuery.prototype上的属性和方法也是jQuery对象的一部分。
4,通过jQuery.fn.extend({...})方式扩展的属性或方法
jQuery.extend扩展和jQuery.fn.extend扩展的区别
首先注意到
注意这一段代码,length代表extend中的参数个数,i初始化为1,如果extend中只有一个参数的话,那么this就赋值给target。
1如果是jQuery.extend 那么this就为function jQuery,也就是说给function jQuery添加了许多静态方法。些方法都可以直接通过jQuery.xx(或$.xx)方式来调用,而不是先执行(调用)jQuery方法再去调用xx,如$("#id").xx。
因此,jQuery中的isFunction, isArray, isWindow等都是静态方法,只能通过$.isFunction, $.isArray, $.Window引用。而不能通过$("...").isFuction, $("...").isArray, $("...").isWindow方式引用。
2.如果是jQuery.fn.extend那么this就为jQuery.protoype ,因为fn为prototype,也就是给jQuery.prototype上添加了许多属性,方法。当jQuery函数执行时,如$()或jQuery(),更多时候是$()。这时则把扩展的属性,方法都附加到new生成的对象上了。(注意prototype的属性就是等到new时,才会原型的所有属性立即赋予要创建的对象上)
因此扩展的属性或方法都添加到jQuery对象上了。如bind, one, unbind等可以通过$("...").bind, $("...").one, $("...").unbind方式调用。却不能通过 $.bind, $.one, $.unbind方式调用。
标识符jQuery,我们可以理解其为一个function,
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
}
而jQuery的fn,我们理解其为prototype,因为jQuery.fn = jQuery.prototype =
{
constructor: jQuery,
init: function(selector, context, rootjQuery){
}
}
还要注意一句话jQuery.fn.init.prototype = jQuery.fn。该句把function jQuery的原型赋值给了function init的原型。
当调用$("#id")时返回的对象组成包括两个部分,由function init中this带的(如this.context);由function jQuery的prototype带的(如this.size/this.toArray);
jQuery对象由以下部分组成:
1,挂在jQuery.prototype.init中的this上的属性或方法。
2,挂在jQuery.prototype.init.prototype上的属性或方法。
3,因为把jQuery.prototype赋值给了jQuery.prototype.init.prototype,所以挂在jQuery.prototype上的属性和方法也是jQuery对象的一部分。
4,通过jQuery.fn.extend({...})方式扩展的属性或方法
jQuery.extend扩展和jQuery.fn.extend扩展的区别
首先注意到
jQuery.extend = jQuery.fn.extend = function() {
...
};
也就是这两种方式的源代码都是相同的,但是他们的主要区别在哪里呢?
if ( length === i ) {
target = this;
--i;
}
注意这一段代码,length代表extend中的参数个数,i初始化为1,如果extend中只有一个参数的话,那么this就赋值给target。
1如果是jQuery.extend 那么this就为function jQuery,也就是说给function jQuery添加了许多静态方法。些方法都可以直接通过jQuery.xx(或$.xx)方式来调用,而不是先执行(调用)jQuery方法再去调用xx,如$("#id").xx。
因此,jQuery中的isFunction, isArray, isWindow等都是静态方法,只能通过$.isFunction, $.isArray, $.Window引用。而不能通过$("...").isFuction, $("...").isArray, $("...").isWindow方式引用。
2.如果是jQuery.fn.extend那么this就为jQuery.protoype ,因为fn为prototype,也就是给jQuery.prototype上添加了许多属性,方法。当jQuery函数执行时,如$()或jQuery(),更多时候是$()。这时则把扩展的属性,方法都附加到new生成的对象上了。(注意prototype的属性就是等到new时,才会原型的所有属性立即赋予要创建的对象上)
因此扩展的属性或方法都添加到jQuery对象上了。如bind, one, unbind等可以通过$("...").bind, $("...").one, $("...").unbind方式调用。却不能通过 $.bind, $.one, $.unbind方式调用。