深入瞭解jQuery之整體架構

來源:互聯網
上載者:User

標籤:obj   something   ima   nbsp   原型   源碼解析   blog   代碼   sel   

本文是在閱讀了Aaron艾倫的jQuery源碼解析(地址:http://www.imooc.com/learn/172)後的個人體會以及筆記。在這裡感謝艾倫老師深入淺出的講解!!

 

先來看看如何產生一個jQuery對象,源碼:

var  jQuery = function( selector, context ) {                return new jQuery.fn.init( selector, context );    };

當我們使用jQuery(‘something‘)或者$(‘something‘)時,我們得到的是一個 jQuery.fn.init()對象。那麼jQuery.fn是什麼鬼?

jQuery.fn = jQuery.prototype = {    // jQuery版本    jquery: version,    constructor: jQuery, // 建構函式    // Start with an empty selector    selector: "",    // The default length of a jQuery object is 0    length: 0,    // 省略.....}

jQuery.fn 實際上是jQuery建構函式的原型對象的引用!! 所以我們以後看到 jQuery.fn時,把他當成jQuery建構函式的原型對象就可以了。

知道了jQuery.fn , 接下來看看jQuery.fn.init()函數

jQuery.fn.init = function( selector, context ) {      //  省略....
return this; };
jQuery.fn.init.prototype = jQuery.prototype; // 注意這裡! 這句代碼讓init對象可以使用jQuery的原型方法。

這樣,我們在建立jQuery對象時就不用使用new關鍵字了。

整體看一下源碼架構:

var $ = jQuery = function(selector,context){    return new jQuery.fn.init(selector,context)  // 返回一個jQuery.fn.init()對象}jQuery.fn = jQuery.prototype = {    constructor:jQuery,    init:function(){        // 省略.....        return  this;    }}jQuery.fn.init.prototype = jQuery.fn

 

直觀的感受一下相互之間的關係:

 

調用jQuery函數,我們得到的是一個jQuery.fn.init執行個體,這個執行個體的原型對象被重新指向到了jQuery函數的原型對象,所以這個執行個體可以使用jQuery原型對象的屬性和方法,而如果我們給jQuery函數附加方法,那麼這個方法就變成了靜態方法。

然後來看一下jQuery.fn.init函數的源碼:

 View Code

 

 配張思路圖:

 

深入瞭解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.