2013-08-28 110 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