標籤:
一、jQuery總體架構
jQuery作為一款強大的js庫,由以下模組構成:
(function(window,undefined){ var jQuery=function(selector,context){ //... }; //工具方法utilities //回呼函數 callbacks //非同步隊列 Defered Object //瀏覽器功能測試 Support //資料緩衝 Data //隊列 Queue //屬性操作 Attributes //事件系統 Events //選取器 Sizzle //DOM遍曆 Traversing //DOM操作 Manipulation //樣式操作 CSS //非同步請求 Ajax //動畫 Animation //座標 offset,尺寸 Dimensions window.jQuery=window.$=jQuery;}})(window);
關於上述代碼,解釋如下:
1.jQuery的整體程式碼封裝裹在一個立即執行的自調用匿名的函數中,這樣可以盡量減少和其他第三方庫的幹擾;
2,在上述代碼最後,將jQuery對象添加到全域window上,並為之設定變數$,從而使得可以在外界訪問jQuery;
3,為自調用匿名函數設定參數window,並傳入參數window,這樣一方面可以縮短範圍鏈,可以儘快訪問到window;另一方面便於代碼壓縮;
4,為自動用匿名函數設定參數undefined,一方面可以縮短尋找Undefined的範圍鏈,另一方面可防止undefined在外界被修改。
二、構造jQuery對象
jQuery對象是一個類數組對象,含有連續的整型屬性、length屬性、context屬性,selector屬性(在jQuery.fn.init中設定),preObject屬性(在pushStack中設定);此外,還包含非繼承屬性以及大量的jQuery方法。
jQuery建構函式根據傳入參數不同,有7種用法,在自己嘗試實現的輕量級jQuery中,暫不考慮傳入複雜選取器運算式和html代碼的情形。
jQuery建構函式的整體代碼結構如下:
(function(window,undefined){ var rootjQuery, jQuery=function(selector,context){ return jQuery.fn.init(selector,context,rootjQuery); }; jQuery.fn=jQuery.prototype={ constructor:jQuery, init:function(selector,context,rootjQuery){ //... } }; jQuery.fn.init.prototype=jQuery.prototype; rootjQuery=jQuery(document); window.jQuery=window.$=jQuery;}})(window);
針對上述代碼,解釋如下:
1)在jQuery建構函式中,使用new建立並返回另一個建構函式的執行個體,這樣可以在建立jQuery對象時,省略運算子new而直接寫jQuery;此時,在建構函式中返回的是jquery.fn.init的執行個體,為了保證能夠在jQuery.fn.init()的執行個體上訪問jQuery()的原型方法和屬性,令 jQuery.fn.init.prototype=jQuery.prototype。
jQuery原始碼閱讀之一——jQuery總體結構及jQuery建構函式