javascript如何在类/对象发生实例化后调用新添加的方法?

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

本文关键字:新添加 调用 添加 方法 实例化 对象 javascript      更新时间:2023-09-26

请告诉我这是怎么回事…

怎么可能,在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"