Javascript 来自具有原型的父代的多重继承
javascript中是否有方法继承多个类的原型: 前 编辑: 不,西红柿不能吃,Javascript 来自具有原型的父代的多重继承,javascript,inheritance,Javascript,Inheritance,javascript中是否有方法继承多个类的原型: 前 编辑: 不,西红柿不能吃, “吃法”的意思是吃食物,而不是食物吃了你我不明白为什么西红柿可以吃任何东西:) 但是,可以在JavaScript中实现某种多重继承。您只需通过从两个父对象原型中获取属性来扩展原型: 功能设备(名称){ this.name=名称; } Plant.prototype.grow=函数(){ document.write(“+this.name+“growing”); function food(){ thi
“吃法”的意思是吃食物,而不是食物吃了你我不明白为什么西红柿可以吃任何东西:) 但是,可以在JavaScript中实现某种多重继承。您只需通过从两个父对象原型中获取属性来扩展原型:
功能设备(名称){
this.name=名称;
}
Plant.prototype.grow=函数(){
document.write(“+this.name+“growing”);
function food(){
this.value_a = 1;
}
food.prototype.eat = function(){
console.log("eats");
}
function plant(){
this.value_b = 2;
}
plant.prototype.grow = function(){
console.log("grows");
}
function tomato(){
food.call(this);
plant.call(this);
this.value_c = 3;
}
Object.assign(tomato.prototype, food.prototype);
Object.assign(tomato.prototype, plant.prototype);
var new_tomato = new tomato();
console.log(new_tomato)
};
函数杀手(名称){
this.name=名称;
}
Killer.prototype.eat=函数(){
文件。写(“+this.name+”eating”);
function food(){
this.value_a = 1;
}
food.prototype.eat = function(){
console.log("eats");
}
function plant(){
this.value_b = 2;
}
plant.prototype.grow = function(){
console.log("grows");
}
function tomato(){
food.call(this);
plant.call(this);
this.value_c = 3;
}
Object.assign(tomato.prototype, food.prototype);
Object.assign(tomato.prototype, plant.prototype);
var new_tomato = new tomato();
console.log(new_tomato)
};
功能番茄(名称){
this.name=名称;
}
用于(工厂中的var键。原型){
番茄.prototype[key]=Plant.prototype[key];
}
for(Killer.prototype中的var键){
番茄.prototype[key]=Killer.prototype[key];
}
var killerTomato=新番茄(“百胜”);
killerTomato.eat();
killerTomato.grow()代码>另一种方法是使用Object.assign()
方法
您是否实现了基于杀手番茄攻击的游戏?:)你能用foreach方法代替for循环吗?foreach是什么意思?for(var…in)是在对象上循环的标准方法,就像你在数组[0,2,4,5]上循环一样。foreach(function(e){})我发现你有Objects.assign函数,所以我可以做Tomato.prototype=Objects.assign(Tomato.prototype,Food.prototype)感谢上面的解决方案,但是其他assign方法,我还评论说,我将使用object.assign,但thxyeah不要忘记为扩展的每个类调用构造函数。否则,您将丢失它们在类初始化期间应该计算的所有属性。