请帮助我理解这是如何发生的......
实例化 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?
最佳答案
它之所以有效,是因为继承是“实时的”。
当你创建一个继承自另一个对象B的对象A时,A当时并没有在本地存储B的属性的副本。相反,它只是在其 [[Prototype]] 中引用 B。
然后,当您尝试访问 A 上的属性但没有具有该名称的自己的属性时,将改为咨询 B。
因此,当您更改某个对象时,可能会影响从该对象继承的所有对象。
var obj = {};
console.log(obj.foo); // undefined
Object.prototype.foo = "bar";
console.log(obj.foo); // "bar"
关于javascript - 类/对象实例化后,javascript 如何调用新添加的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794481/