DIV CSS 佈局教程網

拆解 jQuery 的無 new 建構:兩種實例建立寫法的差異
編輯:關於JavaScript     

第一次讀 jQuery 原始碼時,最讓我卡住的就是 jQuery.fn.init 那套「不寫 new 卻能產生實例」的設計。反覆琢磨之後總算有點眉目,記錄於此。

第一種寫法:直接回傳原型上的 init()

 var A = function(){
    return A.prototype.init();
}
A.prototype = {
    init: function(){
        this.age = 50;
        console.log(this);
        return this;
    },
    age: 100
}
console.log(A() === new A());

為什麼結果是 true?

A() 內部呼叫的是 A.prototype.init();而 new A() 會先執行建構子,它的建構子本體就是 function(){ return A.prototype.init(); },最終同樣呼叫 A.prototype.init()。兩邊走的是同一條路。

那 init() 又回傳什麼?關鍵在 this。判斷 this 要看呼叫當下,這裡它是作為原型物件的屬性被呼叫,所以 this 指向 A.prototype,回傳的自然也是原型本身。

這就帶來一個副作用:不管你呼叫多少次 A(),拿到的其實是同一個物件。

 var a = A();
 var b = A();
 console.log(a.age);   // 50
 console.log(b.age);   // 50
 b.age = 22;
 console.log(a.age);   // 22,被連帶改掉了
 console.log(b.age);   // 22

第二種寫法:jQuery 採用的方式

 var A = function(){
    return new A.prototype.init();   // ①
}
A.prototype = {
    init: function(){
        this.age = 50;
        console.log(this);
        return this;
    },
    age: 100
}
 A.prototype.init.prototype = A.prototype;   // ②

var a = new A();
var b = new A();
console.log(a === b);   // false
console.log(a.age);     // 50
console.log(b.age);     // 50
b.age = 22;
console.log(a.age);     // 50,各自獨立
console.log(b.age);     // 22

① 做了什麼? new A.prototype.init() 基本上完成三件事:建立一個空物件、讓該物件的 __proto__ 指向 A.prototype.init.prototype、把 init 的 this 換成這個新物件後呼叫並回傳它。

② 為何必要?因為 ① 回傳物件的精神原型是 A.prototype.init.prototype,和 A.prototype 之間毫無關聯。把 A.prototype.init.prototype 指向 A.prototype,新的實例才能正確繼承 A 的原型成員,同時又保有各自獨立的作用域。

一句話總結:加上 new 讓每次呼叫都產生新物件,再把 init 的 prototype 接回主原型,就同時解決了「免 new 呼叫」與「狀態互相污染」兩件事。這正是 jQuery 能寫成 $() 卻還有完整原型鏈的原因。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved