我正在阅读有关JavaScript继承的教程,并且有以下声明:
对于Rabbit类继承Animal类的对象,我们需要:
从Animal继承Rabbit:
Rabbit.prototype = new Animal()
他们说这种方法的缺点是需要创建一个冗余对象。我不明白为什么我需要创建那个冗余对象?我尝试过以下操作,但没有创建多余的对象:
function Animal() {};
function Rabbit() {};
Rabbit.prototype = Animal.prototype
Animal.prototype.go = function() {alert("I'm inherited method"};
var r = new Rabbit();
r.go();
我在这里缺少什么?
答案 0 :(得分:3)
您的方法存在严重缺陷,最好通过一个示例来证明:
function Animal() {};
Animal.prototype.feed = function(){
console.log("feeding")
};
function Rabbit() {this.teeth = 4};
Rabbit.prototype = Animal.prototype; // oops
Rabbit.prototype.feed = function(){
if(this.teeth > 1){
console.log("chewing")
} else {
throw "I have no teeth!"
}
}
var leechworm = new Animal;
leechworm.feed(); //throws
因为leechworm
是一个Animal
,无论我们定义什么类型的动物,它都应该能够提供,但由于Animal.prototype === Rabbit.prototype
,Animal.prototype.feed
与Rabbit.prototype.feed
相同{1}}。水蛭会抱怨他缺牙。
答案 1 :(得分:3)
您所缺少的是,使用您的代码,Rabbit
和Animal
共享完全相同的原型。如果您向eatCarrot
添加了Rabbit
方法,那么每个其他Animal
也会使用该方法。
您使用的教程实际上已经过时了。替代子类的首选方法是使用Object.create
为Rabbit创建一个全新的prototype
对象,链接到Animal.prototype
:
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
请注意,不依赖于从Rabbit
的实例继承Animal
。
有关详细信息,请参阅MDN。