jquery源码入口部分解析

作者: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)。




/**简化后的骨架*/
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对象的静态方法哪去了?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值