2015-08-29 53 views
2

我認爲最好的方式來證明我的意思是表明講述的故事本身的代碼...爲什麼在原型鏈上操縱屬性實際上是在對象上創建的?

function Animal() {this.lives=7;} 
function Cat() {} 
Cat.prototype = new Animal(); 
cat1 = new Cat(); 

for (var i in cat1) { if (cat1.hasOwnProperty(i)) { console.log(i);}} 
//undefined --as expected since property lives exists in prototype chain, Cat.prototype. 

//but when i do this 
cat1.lives -= 1; 

// and now if i run this again 
for (var i in cat1) { if (cat1.hasOwnProperty(i)) { console.log(i);}} 
// lives -- How?? I just manipulated property in proto chain i didnt do obj.val = 3; which would create a new property. 

,公正地完成..如果我做

Cat.prototype.lives = 10; 

然後

cat1.prototype.lives; // 6 
+0

什麼是'cat1.prototype.lives'?你的意思是'cat1.lives'? – thefourtheye

+0

cat1沒有自己的生命財產,所以我想如果我做'cat1.lives'並獲得原始鏈中的財產,那麼如果我做'cat1.lives = 3;'然後我改變原始鏈中的財產。 –

回答

3

原型鏈將僅用於解析值。但是當你分配一些東西的時候,這個屬性將會在這個對象上創建。

你能想到的

cat1.lives -= 1; 

cat1.lives = cat1.lives - 1; 

這裏,先右側表達式求值。因此,根據原型鏈,cat1.lives解析爲7。但是,在分配它時,將在cat1對象本身上創建lives屬性。

+0

這就是我認爲它似乎是,當分配財產時,它被賦予對象,即使認爲它可以解決/存在原始鏈。所以要操縱一個屬性,而不是方法,需要定義setters。這是在任何地方記錄。 –

+0

'cat1.lives = cat1.lives - 1;'部分解釋給我,使它適用於我的js邏輯如何工作的模型。 –

相關問題