jQuery原始碼閱讀之一——jQuery總體結構及jQuery建構函式

來源:互聯網
上載者:User

標籤:

一、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建構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.