javascript继承与原型 - 冗余对象

时间:2013-08-28 10:22:18

标签: javascript

我正在阅读有关JavaScript继承的教程,并且有以下声明:

对于Rabbit类继承Animal类的对象,我们需要:

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

    Rabbit.prototype = new Animal()

  4. 他们说这种方法的缺点是需要创建一个冗余对象。我不明白为什么我需要创建那个冗余对象?我尝试过以下操作,但没有创建多余的对象:

    function Animal() {};
    function Rabbit() {};
    Rabbit.prototype = Animal.prototype
    Animal.prototype.go = function() {alert("I'm inherited method"};
    var r = new Rabbit();
    r.go();
    

    我在这里缺少什么?

2 个答案:

答案 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.prototypeAnimal.prototype.feedRabbit.prototype.feed相同{1}}。水蛭会抱怨他缺牙。

答案 1 :(得分:3)

您所缺少的是,使用您的代码,RabbitAnimal共享完全相同的原型。如果您向eatCarrot添加了Rabbit方法,那么每个其他Animal也会使用该方法。

您使用的教程实际上已经过时了。替代子类的首选方法是使用Object.create为Rabbit创建一个全新的prototype对象,链接到Animal.prototype

Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

请注意,依赖于从Rabbit实例继承Animal

有关详细信息,请参阅MDN