繁体   English   中英

带有原型的javascript继承-冗余对象

[英]javascript inheritance with prototype - redundant object

我正在阅读有关JavaScript继承的教程,其中包含以下语句:

为了使Rabbit类的对象能够从Animal类继承,我们需要:

  1. 定义动物
  2. 定义兔子
  3. 从动物继承兔子:

    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.prototypeAnimal.prototype.feedRabbit.prototype.feed相同。 蠕虫会抱怨他缺少牙齿。

您所缺少的是,在您的代码中, RabbitAnimal共享完全相同的原型。 如果您在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM