2010-10-11 56 views
4

如何從繼承對象調用超級構造函數?例如,我有一個簡單的動物「類」:Javascript:原型連貫性和超級構造函數

function Animal(legs) { 
    this.legs = legs; 
} 

我希望創建一個從動物繼承,但組腿部的數量隨機數(提供在腿的最大數目的「奇美拉」級。構造到目前爲止,我有這樣的:?

function Chimera(maxLegs) { 
    // generate [randLegs] maxed to maxLegs 
    // call Animal's constructor with [randLegs] 
} 
Chimera.prototype = new Animal; 
Chimera.prototype.constructor = Chimera; 

如何調用動物的構造感謝

回答

4

我想你想要的是類似constructor chaining

function Chimera(maxLegs) { 
    // generate [randLegs] maxed to maxLegs 
    // call Animal's constructor with [randLegs] 
    Animal.call(this, randLegs); 
} 

或者你可以考慮Parasitic Inheritance

function Chimera(maxLegs) { 

    // generate [randLegs] maxed to maxLegs 
    // ... 

    // call Animal's constructor with [randLegs] 
    var that = new Animal(randLegs); 

    // add new properties and methods to that 
    // ... 

    return that; 
} 
-2

你應該能夠做到這一點:

new Animal(); 
+1

僅供參考,你被低估的原因是,雖然這會調用Animal構造函數,但它不會調用動物構造函數*當前對象*。 – Chuck 2010-10-11 21:04:37

+0

放棄投票似乎是一個極端的事情。你可以糾正我,而不是懲罰我。 – kevin628 2010-10-11 21:18:22

2

可以使用call方法每個功能有:

function Chimera(maxLegs) { 
    var randLegs = ...; 
    Animal.call(this, randLegs); 
} 
+0

我在「Chimera.prototype = new Animal」中出現錯誤;部分因爲我認爲它在實例化時沒有參數調用Animal() – pistacchio 2010-10-11 21:32:49