作者:zccst
读完JavaScript Pattern后,再读jQuery源码感觉轻松很多,其中要点是:
构造函数
原型对象
new Contruction()的执行过程
封装(立即执行函数)
根据上面的概念,jQuery本质也是一个构造函数,但是从始至终,都没有new jQuery对象new jQuery();而仅仅是调用jQuery构造函数,这样构造函数自身,始终都没有使用jQuery的原型发生关联。
把jQuery构造函数当做普通函数调用,内部返回了一个对象(在其构造函数内部转了一个弯)new了原型对象中的Init方法。此时,新的构造函数变成了init方法。init内部的this属性和方法是实例单独拥有的。(很少,只有5个,分别是this.selector, this.context, this.length, this. )
同时让init.prototype = jquery.prototype;以便使用jQuery的原型对象中的属性和方法。
其中,init方法返回的是一个this对象。
this指代new init构造函数创建的对象,里面既有自己的属性和方法,也有共有的属性和方法。
this是jQuery独有的对象,其中DOM数组部分是一个类数组(array like)。
看看具体实例:
$("div.diggit")结果:
1,jQuery对象
0: div.diggit
context: document
length: 1
prevObject: e.fn.e.init[1]
selector: "div.diggit"
__proto__:
2,jQuery对象的原型对象
扩展了N多方法
3,jQuery对象的静态方法哪去了?
读完JavaScript Pattern后,再读jQuery源码感觉轻松很多,其中要点是:
构造函数
原型对象
new Contruction()的执行过程
封装(立即执行函数)
根据上面的概念,jQuery本质也是一个构造函数,但是从始至终,都没有new jQuery对象new jQuery();而仅仅是调用jQuery构造函数,这样构造函数自身,始终都没有使用jQuery的原型发生关联。
把jQuery构造函数当做普通函数调用,内部返回了一个对象(在其构造函数内部转了一个弯)new了原型对象中的Init方法。此时,新的构造函数变成了init方法。init内部的this属性和方法是实例单独拥有的。(很少,只有5个,分别是this.selector, this.context, this.length, this. )
同时让init.prototype = jquery.prototype;以便使用jQuery的原型对象中的属性和方法。
其中,init方法返回的是一个this对象。
this指代new init构造函数创建的对象,里面既有自己的属性和方法,也有共有的属性和方法。
this是jQuery独有的对象,其中DOM数组部分是一个类数组(array like)。
/**简化后的骨架*/
var jQuery = (function() {
var jQuery = function( selector, context ) {
//jQuery对象实际上只是init构造函数“增强”
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
/**
* 入口
* 构造函数 function init(){}
* 原型对象 init.prototype = jQuery.prototype
*/
init: function( selector, context, rootjQuery ) {
return jQuery.makeArray( selector, this );
},
selector: "",
jquery: "1.7.1",
length: 0,
size: function() {return this.length;},
toArray: function() {return slice.call( this, 0 );},
get: function( num ) {},
pushStack: function( elems, name, selector ) {},
each: function( callback, args ) {return jQuery.each( this, callback, args );},
ready: function( fn ) {},
eq: function( i ) {},
first: function() {},
last: function() {},
slice: function() {},
map: function( callback ) {},
end: function() {return this.prevObject || this.constructor(null);},
push: push,
sort: [].sort,
splice: [].splice
};
//让jQuery原型中的init方法中的原型对象指向jQuery的原型
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
//新增静态方法jQuery.extend,新增原型方法jQuery.fn.extend
jQuery.extend = jQuery.fn.extend = function() {
return target;
};
//绑定一堆静态方法
jQuery.extend({
});
return jQuery;
})();
看看具体实例:
$("div.diggit")结果:
1,jQuery对象
0: div.diggit
context: document
length: 1
prevObject: e.fn.e.init[1]
selector: "div.diggit"
__proto__:
2,jQuery对象的原型对象
扩展了N多方法
3,jQuery对象的静态方法哪去了?