JavaScript继承自两个不同的对象

时间:2017-11-20 14:07:33

标签: javascript oop inheritance prototype

鉴于类AnimalFlying_object,我想根据以下规则实例化BirdBoomerang对象:

  • Boomerang必须仅从Flying_object继承。
  • Bird必须继承Animalflying_object

问题:我似乎无法找到将Bird实例化为Animal和Flying_object的正确方法。

我不能让Animal继承Flying_object因为并非所有动物都是飞行物体,我也不能Flying_objectAnimal继承,因为回旋镖不是一只动物。

/**
 * Only Bird must inherit this class
*/
var Animal = function() {
    this.className = 'Animal';
};
Animal.prototype.sayClassName = function() {
    console.log('I am a '+ this.className);
};

/**
 * Both Boomerang and Bird must inherit this class
*/
var Flying_object = function() {
    this.className = 'Flying_object';
};
Flying_object.prototype.sayName = function() {
    console.log('I am a '+ this.className);
};
Flying_object.prototype.fly = function() {
    console.log(this.className +' can fly');
}

尝试将Bird实例化为Animal和Flying_object时出错:

var Bird = function() {
    this.className = 'Bird';
}
Bird.prototype = new Animal();        //----> Bird should inherit from Animal
Bird.prototype = new Flying_object(); //----> It should also inherit from Flying_object
Bird.prototype.sayName = function() {
    console.log('I am a '+ this.className);
};

/**
 * instantiating...    
*/
var bird = new Bird();
bird.sayName();
bird.fly();
bird.isAnimal(); //---> Uncaught TypeError: bird.isAnimal is not a function

我理解为什么会收到此错误:Bird.prototype = new Animal();Bird.prototype = new Flying_object();重载,所以它实际上只是从Flying_object继承而来。问题是我不知道如何解决这个问题。

有什么方法可以让Bird从AnimalFlying_object继承?如果没有,那么让bird分享AnimalFlying_object的所有属性和方法的正确方法是什么?

JSfiddle:https://jsfiddle.net/Hal_9100/9hn30pdz/

0 个答案:

没有答案