2010-05-20 212 views
5

我找到了。它有什麼作用?這是做什麼用的?

function G(a, b) { 
    var c = function() { }; 
    c.prototype = b.prototype; 
    a.T = b.prototype; 
    a.prototype = new c; 
} 
+1

我猜你在問什麼是「爲什麼有人會這樣做?」,因爲除了回答「迷惑人」之外,我沒有任何東西可以幫你。 – wlangstroth 2010-05-20 14:56:04

+1

你從哪裏找到這個?被設置的'T'屬性並不是典型的關於原型繼承的任何模式。 但我相信這可能是有繼承的構造函數以及原型鏈。 – 2010-05-20 15:00:31

回答

1

它看起來類似於Crockford的Object.create方法,但該函數用於「設置」構造函數。

它接受兩個構造函數作爲參數,並且它設置了第一個構造函數的prototype

讓我重新命名神祕的變量名:

function G(sub, super) { 
    var F = function() { }; 
    F.prototype = super.prototype; 
    sub.superLink = super.prototype; 
    sub.prototype = new F(); 
} 

function Super() { 
    //... 
} 
Super.prototype.member1 = 'superMember1'; 

function Sub() { 
    this.member2 = 'subMember2'; 
} 

G(Sub, Super); 

new Sub(); // Object { member2="subMember2", member1="superMember1"} 

編輯:T屬性只是用來知道什麼是子之一的「超級」的構造,我已經看到了這種模式的其他地方,如在書專業JavaScript的設計模式page 43),與一些補充,防止constructor屬性指向了錯誤的對象:

function extend(subClass, superClass) { 
    var F = function() {}; 
    F.prototype = superClass.prototype; 
    subClass.prototype = new F(); 
    subClass.prototype.constructor = subClass; 

    subClass.superclass = superClass.prototype; 
    if(superClass.prototype.constructor == Object.prototype.constructor) { 
     superClass.prototype.constructor = superClass; 
    } 
} 

參見:

+1

我不認爲它那麼簡單,'T'屬性在某種程度上用於這個問題並不清楚。此外,只需設置'Sub.prototype = Super.prototype'就可以達到答案的結果 – 2010-05-20 14:59:14

+1

@Sean不完全。通過這樣做,如果您將一個成員添加到'Sub.prototype',您還會將一個成員添加到'Super.prototype'。 – 2010-05-20 15:17:30

+0

@CMS我認爲值得注意的是'member2'將在'new Sub()'的原型鏈上,而不是在'new Sub()'本身。 – 2010-05-20 15:18:01

0

它看起來像它可以讓你在一個函數時,進行更改,然後傳回的能力 - a.prototype是一個新的實例它的副本。網上有一些例子使用這種類型的代碼來「獲取」和「設置」。