在正式拆解 jQuery 的底層實現之前,我想先整理幾個關鍵知識點。這些都是我一路學習走過來踩過的坑,反覆跌倒之後才慢慢補齊的:
1)先來看一個自訂的建構函數:
function person(){ this.name="aa"; } person(); console.log(window.name);//aa
這個例子用來說明:在全域環境下,函數的執行上下文其實就是 window(全域)物件。由於 this 指向 window,於是無意間就在全域建立了一個 name 變數。一般來說,若不透過 new 來建構,函數內部「this.屬性」會掛到它的父層作用域上;而用 new 建構時,執行上下文會變成一個全新的空上下文,這個上下文代表剛產生的實例。一句話總結:this 永遠指向當前呼叫它的物件,更精確地說,指向它的執行上下文。
2)以「物件[基本資料型別]」這種格式建立的屬性,也只能用同樣的「物件[基本資料型別]」格式去存取。
3)當函數內部又定義了函數時,為了避免 this 指向錯亂,通常在最外層函數裡宣告「var self=this;」,用 self 保存外層的 this,避免和內層函數的 this 混淆。
理解這些之後,我們再來看 jQuery 的實現機制。以下節錄自 jQuery 1.6.1 的的原始碼:
var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, ... class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function(selector, context, rootjQuery){ } } // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn;
把上面這段程式碼濃縮一下就能得到關鍵結論:jQuery.fn.init 是一個建構函數,而由於 jQuery.fn.init.prototype = jQuery.prototype,所以 jQuery.fn.init 所產生的實例,同時也是 jQuery 的實例。也就是說,透過 jQuery.fn.init 建構出來的物件,既能存取 jQuery.fn.init.prototype 上的屬性與方法,也能存取 jQuery.prototype 上的屬性與方法。
順著這個思路,我們自己也能寫出一段類似的程式碼:
//創建一個jquery構造函數 function jQuery(selector){ return new jQuery.fn.init(selector); //返回一個jQuery對象,可以訪問jQuery.fn.init.prototype與jQuery.prototype中屬性 } //添加一個init函數給jQuery.fn jQuery.fn=jQuery.prototype={ constructor:jQuery, init:function(selector){ //通過init構造函數可以保持生產選取到dom節點的對象 if(selector==="undefined"){this.length=0;return this;}//未選擇 if(selector.nodeType==1){this[0]=selector;}else{this[0]=document.getElementById(selector);} //這裡this[0]指創建此jQuery實例對象的屬性0,且訪問格式只能是此jQuery對象[0] this.length=1; //給jQuery對象添加一個length屬性 }, css:function(name,value){ this[0].style[name]=value; return this; //鏈式調用 ,這裡this指css()的調用者--jquery的實例對象,而不是css構造出來的實例對象,返回jQuery對象 }, hide:function(){ var self=this; setTimeout(function(){ self[0].style.display="none"; //self[0]為選取的Dom節點對象 },2000); return this; //鏈式調用,通過jQuery原型的實例對象獲取 }, float:function(position){ this[0].style.float=position; return this; //鏈式調用,返回此時調用的jQuery對象 } } //將jQuery原型賦給jQuery.fn.init的原型,讓init可以生產jQuery的實例 jQuery.fn.init.prototype=jQuery.prototype;
我的註解或許寫得有點零碎,但作為學習筆記,我盡量寫得詳細一些。相信搭配這些註解加上你的思考,理解起來並不困難。
必須補充的是,這段程式碼只能選取帶有 id 的標籤元素,並提供改變定位、隱藏以及修改 CSS 樣式的功能。下面用一段程式碼來測試:
<p id="qq">234</p> <script type="text/javascript"> jQuery("qq").float("right").hide(); </script>
在我這邊功能是完全可以跑起來的,不知道你測試的結果如何?如果遇到問題,歡迎留言討論。