带有原型冗余对象的javascript继承
我正在阅读一篇关于JavaScript继承的教程,其中有以下声明: 要从Animal类继承Rabbit类的对象,我们需要:带有原型冗余对象的javascript继承,javascript,Javascript,我正在阅读一篇关于JavaScript继承的教程,其中有以下声明: 要从Animal类继承Rabbit类的对象,我们需要: 定义动物 定义兔子 从动物身上继承兔子: Rabbit.prototype=新动物() 他们说这种方法的缺点是需要创建冗余对象。我不明白为什么我需要创建那个多余的对象?我尝试了以下方法,但没有创建冗余对象: function Animal() {}; function Rabbit() {}; Rabbit.prototype = Animal.prototype Anim
function Animal() {};
function Rabbit() {};
Rabbit.prototype = Animal.prototype
Animal.prototype.go = function() {alert("I'm inherited method"};
var r = new Rabbit();
r.go();
我在这里遗漏了什么?您的方法有一个严重的缺陷,最好通过一个例子来说明:
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
由于水蛭是一种
动物
,无论我们定义什么样的动物,它都应该能够进食,但是由于Animal.prototype===Rabbit.prototype
,Animal.prototype.feed
与Rabbit.prototype.feed
相同。蚂蚱会抱怨自己缺少牙齿。你的方法有一个严重的缺陷,最好用一个例子来说明:
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
由于水蛭是一种
动物
,无论我们定义什么样的动物,它都应该能够进食,但是由于Animal.prototype===Rabbit.prototype
,Animal.prototype.feed
与Rabbit.prototype.feed
相同。蚂蚱会抱怨自己缺少牙齿。你缺少的是,在你的代码中,兔子
和动物
拥有完全相同的原型。如果您将eatCarrot
方法添加到Rabbit
中,则其他所有Animal
也会使用该方法
您正在使用的教程实际上有些过时。子类化的首选方法是使用对象。create
为兔子创建一个全新的原型
对象,该对象链接到动物。原型
:
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
请注意,这并不取决于从动物
的实例中对兔子
进行子类化
有关更多信息,请参阅。您缺少的是,在代码中,
兔子
和动物
共享完全相同的原型。如果您将eatCarrot
方法添加到Rabbit
中,则其他所有Animal
也会使用该方法
您正在使用的教程实际上有些过时。子类化的首选方法是使用对象。create
为兔子创建一个全新的原型
对象,该对象链接到动物。原型
:
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
请注意,这并不取决于从动物
的实例中对兔子
进行子类化
有关更多信息,请参阅