jQuery2.0.3大体框架:
jQuery2.0.3总体架构如下:
(function( window, undefined ) {
})( window );
jquery-2.0.3,总体看是一个匿名函数自执行,导入js文件后,就会立即执行,同时可以封装内部的变量,避免变量污染。
内部声明的jQuery函数。
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
}
挂载到外部的全局对象window上,使得可以调用。
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
也就是说,每次使用的jquery或者$都是jQuery插件内的一个函数(函数在JavaScript是一种特殊的对象),使用jQuery()或者$()时,返回的是构造函数jQuery.fn.init的一个实例对象。
jQuery.fn.init函数:
jQuery.fn.init函数,在jQuery.prototype的原型中。大致结构如下:
jQuery.fn = jQuery.prototype = {
//......其他属性
init: function( selector, context, rootjQuery ) {
//......函数代码
},
};
jQuery.fn.init.prototype = jQuery.fn;
即,jQuery作为函数时,返回的对象,是构造函数init的一个实例对象。init函数,是jQuery构造函数时的原型中的一个属性,也是jQuery作为对象时的fn中的一个属性。而init的原型,等于jQuery函数的原型。
其中jQuery.fn在这里起到一个中间桥梁的作用,也可以换成这样。
jQuery.prototype = {
//......其他属性
init: function( selector, context, rootjQuery ) {
//......函数代码
},
};
jQuery.prototyp.init.prototype = jQuery.prototyp;
将jQuery.fn删掉之后,对于init与jQuery的关系,大概能清楚不少。
大致的结构图可以是这样:
小结:
可以简单的看出,jQuery在外部两种使用方式,一种是当作函数,根据输入的参数,返回new jQuery.fn.init( selector, context, rootjQuery ),另一种则是直接当作一个对象使用。