轉載Aaron部落格 ---- jQuery 2.0.3 源碼分析core - 整體架構

來源:互聯網
上載者:User

標籤:

jQuery 2.0.3 源碼分析core - 整體架構整體架構

拜讀一個開源架構,最想學到的就是設計的思想和實現的技巧。

廢話不多說,jquery這麼多年了分析都寫爛了,老早以前就拜讀過,

不過這幾年都是做移動端,一直禦用zepto, 最近抽出點時間把jquery又給掃一遍

我也不會照本宣科的翻譯源碼,結合自己的實際經驗一起拜讀吧!

github上最新是jquery-master,加入了AMD規範了,我就以官方最新2.0.3為準

 

整體架構

jQuery架構的核心就是從HTML文檔中匹配元素並對其執行操作、

例如:

$().find().css()$().hide().html(‘....‘).hide().

從上面的寫法上至少可以發現2個問題

1. jQuery對象的構建方式

2 .jQuery方法的調用方式

 

分析一:jQuery的無new構建

JavaScript是函數式語言,函數可以實作類別,類就是物件導向編程中最基本的概念

var aQuery = function(selector, context) {        //建構函式}aQuery.prototype = {    //原型    name:function(){},    age:function(){}}var a = new aQuery();a.name();

這是常規的使用方法,顯而易見jQuery不是這樣玩的

jQuery沒有使用new運行符將jQuery顯示的執行個體化,還是直接調用其函數

按照jQuery的抒寫方式

$().ready() $().noConflict()

要實現這樣,那麼jQuery就要看成一個類,那麼$()應該是返回類的執行個體才對

所以把代碼改一下:

按 Ctrl+C 複製代碼按 Ctrl+C 複製代碼

通過new aQuery(),雖然返回的是一個執行個體,但是也能看出很明顯的問題,死迴圈了!

 

那麼如何返回一個正確的執行個體?

在javascript中執行個體this只跟原型有關係

那麼可以把jQuery類當作一個Factory 方法來建立執行個體,把這個方法放到jQuery.prototye原型中

var aQuery = function(selector, context) {       return  aQuery.prototype.init();}aQuery.prototype = {    init:function(){        return this;    }    name:function(){},    age:function(){}}

當執行aQuery() 返回的執行個體:

很明顯aQuery()返回的是aQuery類的執行個體,那麼在init中的this其實也是指向的aQuery類的執行個體

問題來了init的this指向的是aQuery類,如果把init函數也當作一個構造器,那麼內部的this要如何處理?

按 Ctrl+C 複製代碼按 Ctrl+C 複製代碼

這樣的情況下就出錯了,因為this只是指向aQuery類的,所以需要設計出獨立的範圍才行

 

jQuery架構分隔範圍的處理

jQuery = function( selector, context ) {        // The jQuery object is actually just the init constructor ‘enhanced‘        return new jQuery.fn.init( selector, context, rootjQuery );    },

很明顯通過執行個體init函數,每次都構建新的init執行個體對象,來分隔this,避免互動混淆

那麼既然都不是同一個對象那麼肯定又出現一個新的問題

例如:

var aQuery = function(selector, context) {       return  new aQuery.prototype.init();}aQuery.prototype = {    init: function() {        this.age = 18        return this;    },    name: function() {},    age: 20}//Uncaught TypeError: Object [object Object] has no method ‘name‘ console.log(aQuery().name())

拋出錯誤,無法找到這個方法,所以很明顯new的init跟jquery類的this分離了

 

怎麼訪問jQuery類原型上的屬性與方法?

     做到既能隔離範圍還能使用jQuery原型對象的範圍呢,還能在返回執行個體中訪問jQuery的原型對象?

實現的關鍵點

// Give the init function the jQuery prototype for later instantiationjQuery.fn.init.prototype = jQuery.fn;

通過原型傳遞解決問題,把jQuery的原型傳遞給jQuery.prototype.init.prototype

換句話說jQuery的原型對象覆蓋了init構造器的原型對象

因為是引用傳遞所以不需要擔心這個循環參考的效能問題

var aQuery = function(selector, context) {       return  new aQuery.prototype.init();}aQuery.prototype = {    init: function() {        return this;    },    name: function() {        return this.age    },    age: 20}aQuery.prototype.init.prototype = aQuery.prototype;console.log(aQuery().name()) //20

百度借網友的一張圖,方便直接理解:

fn解釋下,其實這個fn沒有什麼特殊意思,只是jQuery.prototype的引用

 

分析二:鏈式調用

DOM鏈式調用的處理:

1.節約JS代碼.

2.所返回的都是同一個對象,可以提高代碼的效率

 

通過簡單擴充原型方法並通過return this的形式來實現跨瀏覽器的鏈式調用。

利用JS下的簡單原廠模式,來將所有對於同一個DOM對象的操作指定同一個執行個體。

這個原理就超簡單了

aQuery().init().name()分解a = aQuery();a.init()a.name()

把代碼分解一下,很明顯實現鏈式的基本條件就是執行個體this的存在,並且是同一個

aQuery.prototype = {    init: function() {        return this;    },    name: function() {        return this    }}

所以我們在需要鏈式的方法訪問this就可以了,因為返回當前執行個體的this,從而又可以訪問自己的原型了

aQuery.init().name()

優點:節省代碼量,提高代碼的效率,代碼看起來更優雅

最糟糕的是所有對象的方法返回的都是對象本身,也就是說沒有傳回值,這不一定在任何環境下都適合。


Javascript是無阻塞語言,所以他不是沒阻塞,而是不能阻塞,所以他需要通過事件來驅動,非同步來完成一些本需要阻塞進程的操作,這樣處理只是同步鏈式,非同步鏈式jquery從1.5開始就引入了Promise,jQuery.Deferred後期在討論。

 

分析三:外掛程式介面

jQuery的主體架構就是這樣,但是根據一般設計者的習慣,如果要為jQuery或者jQuery prototype添加屬性方法,同樣如果要提供給開發人員對方法的擴充,從封裝的角度講是不是應該提供一個介面才對,字面就能看懂是對函數擴充,而不是看上去直接修改prototype.友好的使用者介面,

jQuery支援自己擴充屬性,這個對外提供了一個介面,jQuery.fn.extend()來對對象增加方法

從jQuery的源碼中可以看到,jQuery.extend和jQuery.fn.extend其實是同指向同一方法的不同引用

jQuery.extend = jQuery.fn.extend = function() {
jQuery.extend 對jQuery本身的屬性和方法進行了擴充jQuery.fn.extend 對jQuery.fn的屬性和方法進行了擴充

通過extend()函數可以方便快速的擴充功能,不會破壞jQuery的原型結構

jQuery.extend = jQuery.fn.extend = function(){...}; 這個是連等,也就是2個指向同一個函數,怎麼會實現不同的功能呢?這就是this 力量了!

針對fn與jQuery其實是2個不同的對象,在之前有講述:

  • jQuery.extend 調用的時候,this是指向jQuery對象的(jQuery是函數,也是對象!),所以這裡擴充在jQuery上。
  • 而jQuery.fn.extend 調用的時候,this指向fn對象,jQuery.fn 和jQuery.prototype指向同一對象,擴充fn就是擴充jQuery.prototype原型對象。
  • 這裡增加的是原型方法,也就是對象方法了。所以jQuery的api中提供了以上2中擴充函數。

extend的實現

jQuery.extend = jQuery.fn.extend = function() {    var src, copyIsArray, copy, name, options, clone,        target = arguments[0] || {},    // 常見用法 jQuery.extend( obj1, obj2 ),此時,target為arguments[0]        i = 1,        length = arguments.length,        deep = false;    // Handle a deep copy situation    if ( typeof target === "boolean" ) {    // 如果第一個參數為true,即 jQuery.extend( true, obj1, obj2 ); 的情況        deep = target;  // 此時target是true        target = arguments[1] || {};    // target改為 obj1        // skip the boolean and the target        i = 2;    }    // Handle case when target is a string or something (possible in deep copy)    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {  // 處理奇怪的情況,比如 jQuery.extend( ‘hello‘ , {nick: ‘casper})~~        target = {};    }    // extend jQuery itself if only one argument is passed    if ( length === i ) {   // 處理這種情況 jQuery.extend(obj),或 jQuery.fn.extend( obj )        target = this;  // jQuery.extend時,this指的是jQuery;jQuery.fn.extend時,this指的是jQuery.fn        --i;    }    for ( ; i < length; i++ ) {        // Only deal with non-null/undefined values        if ( (options = arguments[ i ]) != null ) { // 比如 jQuery.extend( obj1, obj2, obj3, ojb4 ),options則為 obj2、obj3...            // Extend the base object            for ( name in options ) {                src = target[ name ];                copy = options[ name ];                // Prevent never-ending loop                if ( target === copy ) {    // 防止自引用,不贅述                    continue;                }                // Recurse if we‘re merging plain objects or arrays                // 如果是深拷貝,且被拷貝的屬性值本身是個對象                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {                    if ( copyIsArray ) {    // 被拷貝的屬性值是個數組                        copyIsArray = false;                        clone = src && jQuery.isArray(src) ? src : [];                    } else {    被拷貝的屬性值是個plainObject,比如{ nick: ‘casper‘ }                        clone = src && jQuery.isPlainObject(src) ? src : {};                    }                    // Never move original objects, clone them                    target[ name ] = jQuery.extend( deep, clone, copy );  // 遞迴~                // Don‘t bring in undefined values                } else if ( copy !== undefined ) {  // 淺拷貝,且屬性值不為undefined                    target[ name ] = copy;                }            }        }    }    // Return the modified object    return target;

 

 

 

總結:

  • 通過new jQuery.fn.init() 構建一個新的對象,擁有init構造器的prototype原型對象的方法
  • 通過改變prorotype指標的指向,讓這個新的對象也指向了jQuery類的原型prototype
  • 所以這樣構建出來的對象就繼續了jQuery.fn原型定義的所有方法了

轉載Aaron部落格 ---- jQuery 2.0.3 源碼分析core - 整體架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.