[英]javascript inheritance with prototype - redundant object
我正在阅读有关JavaScript继承的教程,其中包含以下语句:
为了使Rabbit类的对象能够从Animal类继承,我们需要:
从动物继承兔子:
Rabbit.prototype =新Animal()
他们说这种方法的缺点是需要创建冗余对象。 我不明白为什么需要创建该冗余对象? 我尝试了以下操作,但没有创建多余的对象就可以了:
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
由于水leechworm
是一种Animal
,所以无论我们定义哪种Animal
,它都应该能够喂食,但是由于Animal.prototype === Rabbit.prototype
, Animal.prototype.feed
与Rabbit.prototype.feed
相同。 蠕虫会抱怨他缺少牙齿。
您所缺少的是,在您的代码中, Rabbit
和Animal
共享完全相同的原型。 如果您在Rabbit
添加了eatCarrot
方法,则其他所有Animal
也将具有该方法。
您正在使用的教程实际上有些过时了。 首选的子类化方法是使用Object.create
为Rabbit创建一个全新的prototype
对象,该对象链接到Animal.prototype
:
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
请注意,这不依赖于继承的Rabbit
从一个实例 Animal
。
有关更多信息,请参见MDN 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.