2016-09-30 47 views
1

請幫我明白這是怎麼發生的?在實例化類/對象後,javascript如何調用新添加的方法?

這怎麼可能,經過myObject的實例化,我可以添加新的方法,以我原來的類/對象的構造函數,並得到兩個結果...

我希望我會以實例mathX爲myObject2得到這個工作...

// make class/object with properties & methods 
 
function mathX(num1, num2) { 
 
    this.factor = 10; 
 
    this.num1 = num1; 
 
    this.num2 = num2; 
 
    this.multiplySum = function() { 
 
     return (this.num1 + this.num2) * this.factor; 
 
    } 
 
} 
 

 
// instantiate class/object with properties & methods 
 
var myObject = new mathX(5, 5); 
 

 
document.write("multiplySum result = " + myObject.multiplySum() + "<br>"); 
 

 
// add new method to class/object AFTER instantiation 
 
mathX.prototype.sumAll = function() { 
 
    return this.num1 + this.num2 + this.factor; 
 
} 
 

 
// immediately use new method on previously instantiated class/object 
 
document.write("sumAll result = " + myObject.sumAll() + "<br>"); 
 

 
// how is this possible? Shouldn't this fail? 
 

 
// How does javasript call a newly added method after instantiation of the class/object occured?

+0

是的,因爲JavaScript使用'object'相同的標記。如果你不想要這個,你需要創建一個深層副本。 – Davide

+0

myObject是一個**引用**到一個mathX對象,然後改變 – Liam

回答

1

它的工作原理,因爲inher itance是「活的」。

當您創建從另一個對象B繼承的對象A時,A當時不在本地存儲B的屬性的副本。相反,它僅在其[[Prototype]中引用B)。

然後,當您試圖訪問A上的一個屬性,但沒有該名稱的自己的屬性時,B將被查詢。

所以當你改變一個對象時,你可能會影響所有繼承它的對象。

var obj = {}; 
 
console.log(obj.foo); // undefined 
 
Object.prototype.foo = "bar"; 
 
console.log(obj.foo); // "bar"

+0

因此,您在說方法A和對象B都存在...但它們之間有一個引用 - 即使它們具有相同的名稱?所以在我的例子中,我有mathX.prototype.sumAll()作爲附加到原始對象的新方法...是否存儲在某個地方作爲原始mathx對象的改進副本?謝謝你的解釋。 – n8thanael

+0

'sumAll'被存儲爲'mathX.prototype'的屬性。它可能在所有從'mathX.prototype'繼承的對象上可用,即使它們是之前創建的。 – Oriol

+0

我也必須有一個定義問題。我以爲sumAll()是一種方法。但是,從來沒有,我認爲我也不理解javascript引用對象'活'的方式 - 我以前的理解是,它們以某種方式像文檔一樣重複寫入內存。我想這是來自學習PHP第一次...或者也許只是一個noob:-J – n8thanael