请帮助我了解这是怎么回事...
实例化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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句