當我們使用$()時到底發(fā)生了什么
1.$是jQuery的別名,$()和jQuery是等價的
window.jQuery = window.$ = jQuery;
2.jQuery構(gòu)造函數(shù)
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
在javascript中,構(gòu)造函數(shù)如果有返回值時,運算符 new所創(chuàng)建的對象會被丟棄,返回值將作為new表達式的值,jQuery利用了這一特性,通過在構(gòu)造函數(shù)jQuery()內(nèi)部用運算符new創(chuàng)建并返回另一個構(gòu)造函數(shù)的實例,省去了構(gòu)造函數(shù)jQuery()前面的new,即我們創(chuàng)建jQuery對象時可以省略new,直接寫jQuery()。
3.jQuery.fn和jQuery.prototype 是等價的
jQuery.fn = jQuery.prototype
4.既然jQuery()構(gòu)造函數(shù)返回的是jQuery.fn.init()構(gòu)造函數(shù)產(chǎn)生的實例,那么代碼中所有掛載在jQuery.fn上的函數(shù),jQuery()創(chuàng)建的實例是不能調(diào)用的。因為jQuery(),jQuery.fn.init()兩個構(gòu)造函數(shù)的原型不一樣產(chǎn)生的實例也是不同的,jQuery是通過下面的代碼解決的。
// Give the init function the jQuery prototype for later instantiation
init = jQuery.fn.init = function( selector, context, root ) {
}
init.prototype = jQuery.fn;
5.當我們使用$()時就是返回了一個 以jQuery.fn.init( selector, context )為構(gòu)造函數(shù)的對象,這個對象的原型是jQuery.
模仿這個過程的小例子
<script type="text/javascript">
var Q=function(){
return new Q.fn.init();
}
Q.fn=Q.prototype;
Q.fn.init=function(){
return this;
}
Q.sayhi=function(){
console.log('hi');
}
Q.fn.sayHello=function(){
console.log('hello');
}
Q.fn.init.prototype=Q.prototype;//如果去掉這一行 下面的qq.sayHello() 無法執(zhí)行
Q.sayhi();
var qq = Q();
console.log(qq);
qq.sayHello();
</script>
參考資料
1.jQuery技術(shù)內(nèi)幕:深入解析jQuery架構(gòu)設(shè)計與原理實現(xiàn) -- 高云