gpt4 book ai didi

Javascript:原型(prototype)继承和 super 构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:51:31 24 4
gpt4 key购买 nike

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

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的构造函数?谢谢

最佳答案

我想你想要的类似于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;
}

关于Javascript:原型(prototype)继承和 super 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com