2013-08-28 112 views
0

我在读一本关于JavaScript中继承的教程,并有下面的语句:Javascript继承与原型 - 冗余对象

兔类的一个对象从动物类继承,我们需要:

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

    Rabbit.prototype =新动物()

他们说这种方法的缺点是需要创建一个冗余对象。我不明白为什么我需要创建多余的对象?我已经尝试了下面的方法,它没有创建多余的对象:

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

我在这里错过了什么?

回答

3

你缺少的是你的代码RabbitAnimal分享完全相同的原型。如果您将eatCarrot方法添加到Rabbit那么每隔一个Animal也会使用该方法。

您正在使用的教程实际上已经过时了。子类,而不是首选的方法是使用Object.create创建一个全新的prototype对象兔子是链到Animal.prototype

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

注意这并依赖于从一个实例继承的RabbitAnimal

请参阅MDN了解更多信息。

+0

+1指出'Object.create' –

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 

因为leechwormAnimal,它应该能够不管我们定义什么样的动物饲料,但由于Animal.prototype === Rabbit.prototypeAnimal.prototype.feedRabbit.prototype.feed相同。蚯蚓会抱怨他缺乏牙齿。

+1

呵呵,我们想出了非常类似的类比:) – Alnitak