2016-12-31 86 views
0

我做了一個快速搜索,但似乎無法找到這個問題的答案,只是指繼承時複製函數原型。 爲什麼不將屬性添加到構造函數原型obj中,而不是使用this關鍵字。我確信有一個理由不會,但我想更好地理解JavaScript的細微差別。例如在正常的原型繼承中,你會「this」。原型繼承和原型對象,爲什麼不用這個程度?

function Dog(name,age,breed){ 
     this.name=name; 
     this.age=age; 
     this.breed=breed; 
} 
Dog.prototype.bark=function(){console.log("bark bark bark");} 

let spike=new Dog("Spike",6,"lab"); 
let rover=new Dog("Rover",8,"poodle"); 


//^with the constructor function, no instance has the bark function but 
//but refers to the same function on the constructor prototype obj, so the 
//same function isn't being duplicated. However new keyword changes the 
//context of this to refer to the obj so these properties are duplicated 
//on every instance. 

//I'm curious as to the reason why new doesn't change this to refer to the 
//prototype obj for example and then have the instance refers its 
//constructor's prototype like with the bark function? 

//for example why isn't this a common pattern and what are the reasons I 
//should use it. 


function Dog(name,age,breed){ 
     Dog.prototype.name=name; 
     Dog.prototype.age=age; 
     Dog.prototype.breed=breed; 
} 

let spike=new Dog("Spike",6,"lab"); 
let rover=new Dog("rover",8,"poodle"); 


//I feel like the above code would be more DRY, I'm sure there is a reason 
// this isn't common and I'm curious as to why 
+0

看看'spike.name'是什麼時候你做你的方式,你會明白爲什麼人們不這樣做你的方式。 – user2357112

回答

3

當你在原型有properties,你將覆蓋與新值每次實例化,即在你的榜樣類的時間屬性,從兩個語句如下:

let spike=new Dog("Spike",6,"lab"); 

let rover=new Dog("rover",8,"poodle"); 

這裏,根據根據您的預期,spike.name應該是Spikerover.name應該是rover,但是如果您執行此代碼並檢查,它們都是rover

當您創建新實例rover時,spike的屬性將被rover的屬性覆蓋。 每次創建一個新的實例時,屬性都被覆蓋,其原因是 methodsproperties附加到原型只創建一次,每次創建新實例時都會繼承到它們的子類

我們從中創建構造函數和新實例的原因是因爲我們對每個實例都有不同的屬性,如Spikerover。在方法的情況下,方法對於構造函數是通用的,對於每次創建新實例時不需要創建的所有實例,這些方法都可以重複使用,因此,我們將它們附加到prototype而不是在構造函數中使用this關鍵字進行定義。