請幫我明白這是怎麼發生的?在實例化類/對象後,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?
是的,因爲JavaScript使用'object'相同的標記。如果你不想要這個,你需要創建一個深層副本。 – Davide
myObject是一個**引用**到一個mathX對象,然後改變 – Liam