2015-01-21 37 views
-1

我叫console.log(Family.prototype.money),值爲200,這證實asset是功能Family的原型。但是當我打電話給console.log(other.money)時,其值爲1000,這是我在原型之前分配的。這裏有什麼問題?它看起來像其他對象的原型不同於功能家族的原型,這與我從書「面向對象的Javascript」中讀到的內容完全矛盾。爲什麼原型中的屬性值不一致?

 function Family(father, mother, children){ 
      this.father = father, 
      this.mother = mother, 
      this.children = children, 
      this.num = function(){ 
       return (this.children.length+2); 
      } 

     }  


     Family.prototype.money = 1000; // notice!!!! 

     var myFamily = new Family('Hung', 'Hong', ['Phuong', 'Lien', 'Hiep']); 
     var other = new myFamily.constructor('Lan', 'Linh', ['Tung']); 

     var money = other.money; 

     var asset = { 
      money: 200, 
      car: 2, 
      house: 10 
     } 
     Family.prototype = asset; 
+2

這並不矛盾 - 你要替換的對象的原型,但其他對象仍參照原始原型。不知道爲什麼你認爲這個操作必須傳播。 – zerkms 2015-01-21 01:59:30

+0

'var a = 1,b = a; a = 2;'你現在期望'b'是'1'還是'2'? – zerkms 2015-01-21 02:00:16

+0

我不能按照你的問題。 – zerkms 2015-01-21 02:09:09

回答

0

函數的prototype不是實例對象的實際原型。當您使用new時,prototype對象將用作內部[[Prototype]]屬性的模板,該屬性在某些瀏覽器中顯示爲__proto__。所以,你改變prototype之前這種表達true

Family.prototype === other.__proto__ // true 
Family.prototype = asset; 

你chnge後,它是false

Family.prototype = asset; 
Family.prototype === other.__proto__ // false 
+0

你能告訴我如何返回實例對象的原型嗎? – PMH 2015-01-21 02:11:03

+0

'object.prototype' – zerkms 2015-01-21 02:11:22

+0

它不起作用。當我調用console.log(other.prototype)時,控制檯日誌返回undefined; – PMH 2015-01-21 02:17:00

相關問題