具有原型的父母的多重继承

时间:2016-05-13 08:29:06

标签: javascript inheritance

javascript中是否有一种方法可以继承多个类的原型:

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)

编辑:

番茄不吃, 吃法意味着吃的不是食物吃的食物

2 个答案:

答案 0 :(得分:1)

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

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

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();

答案 1 :(得分:1)

另一种方法是使用Object.assign()方法。

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)