鉴于类Animal
,Flying_object
,我想根据以下规则实例化Bird
和Boomerang
对象:
Boomerang
必须仅从Flying_object
继承。 Bird
必须继承Animal
和flying_object
。 问题:我似乎无法找到将Bird实例化为Animal和Flying_object的正确方法。
我不能让Animal
继承Flying_object
因为并非所有动物都是飞行物体,我也不能Flying_object
从Animal
继承,因为回旋镖不是一只动物。
/**
* 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从Animal
和Flying_object
继承?如果没有,那么让bird
分享Animal
和Flying_object
的所有属性和方法的正确方法是什么?