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/