4

如何从继承对象调用超级构造函数?例如,我有一个简单的动物“类”:

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

我想创建一个从 Animal 继承但将腿数设置为随机数的“Chimera”类(在构造函数中提供最大腿数。到目前为止,我有这个:

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

如何调用 Animal 的构造函数?谢谢

4

3 回答 3

4

我认为您想要的类似于构造函数链接

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

或者你可以考虑寄生继承

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;
}
于 2010-10-11T21:00:37.327 回答
2

您可以使用call每个函数都有的方法:

function Chimera(maxLegs) {
   var randLegs = ...;
   Animal.call(this, randLegs);
}
于 2010-10-11T20:55:32.607 回答
-2

你应该能够做到这一点:

new Animal();
于 2010-10-11T20:53:14.337 回答