gpt4 book ai didi

javascript - 具有原型(prototype)的 parent 的多重继承

转载 作者:行者123 更新时间:2023-11-30 16:04:49 25 4
gpt4 key购买 nike

javascript有没有办法继承多个类的原型(prototype):

function food(){
}

food.prototype.eat = function(){}

function plant(){
}

plant.prototype.grow = function(){}


function tomato(){
} // needs to have grow and eat methods (and if possible in proto type)

编辑:

不,西红柿不吃,eat方法意味着吃食物而不是食物吃掉你

最佳答案

我不明白为什么西红柿可以吃任何东西:)

但是,可以在 JavaScript 中实现某种多重继承。您只需要通过从两个父对象原型(prototype)中获取属性来扩展原型(prototype):

function Plant(name) {
this.name = name;
}
Plant.prototype.grow = function() {
document.write("<pre>" + this.name + " growing </pre>");
};

function Killer(name) {
this.name = name;
}
Killer.prototype.eat = function() {
document.write("<pre>" + this.name + " eating </pre>");
};

function Tomato(name) {
this.name = name;
}

for (var key in Plant.prototype) {
Tomato.prototype[key] = Plant.prototype[key];
}

for (var key in Killer.prototype) {
Tomato.prototype[key] = Killer.prototype[key];
}

var killerTomato = new Tomato("yum-yum");

killerTomato.eat();
killerTomato.grow();

关于javascript - 具有原型(prototype)的 parent 的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37205026/

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