在jQuery源碼中苇瓣,jQuery是一個(gè)構(gòu)造函數(shù),
而這個(gè)特殊的構(gòu)造函數(shù)使得 “ jQuery() ” 就可以構(gòu)造出jQuery對(duì)象,而不用 “ new jQuery() ”
其中jQuery的構(gòu)造函數(shù)非常特殊聚凹,今天看了一位大神的博文,收獲很多抽诉,稍加整理
寫成今天這篇筆記陨簇。今天是我第一次感受到,js 中 this 的魅力;
jQuery 的構(gòu)造函數(shù)結(jié)構(gòu)大概是這樣的
(function(window){
var jQuery = function( selector, context ) { //jquery 的構(gòu)造函數(shù).
return new jQuery.fn.init( selector, context );
};
jQuery.fn = jQuery.prototype = { //jQuery的原型鏈.
b:3
};
//定義jQuery原型鏈下的init函數(shù).
var init = jQuery.fn.init = function( selector, context, root ){
this.a = 3;
}
//通過window將閉包函數(shù)中的jQuery變量迹淌,變?yōu)楣沧兞?
window.$ = window.jQuery = jQuery;
})(window)
console.log($().a) //3
console.log($().b) //結(jié)果為undefined
問題出現(xiàn)了河绽,new jQuery.fn.init( selector, context )
語句并沒有將jQuery.prototype 下的屬性初始化,而僅僅是將
init函數(shù)下面的屬性初始化了唉窃,問題出現(xiàn)在了 "init.prototype" 上;
關(guān)鍵的語句
init.prototype = jQuery.fn;
這樣完整的代碼應(yīng)該是這樣的:
(function(window){
var jQuery = function( selector, context ) { //jquery 的構(gòu)造函數(shù).
return new jQuery.fn.init( selector, context );
};
jQuery.fn = jQuery.prototype = { //jQuery的原型鏈.
b:3
};
//定義jQuery原型鏈下的init函數(shù).
var init = jQuery.fn.init = function( selector, context, root ){
this.a = 3;
}
//將jQuer.prototype 賦給 init.prototype
init.prototype = jQuery.fn;
//通過window將閉包函數(shù)中的jQuery變量耙饰,變?yōu)楣沧兞?
window.$ = window.jQuery = jQuery;
})(window)
console.log($().b) //3
在改變了 init.prototype 后輸出正常了。