function A() {}
A.prototype.x = 10;
var a = new A();
alert(a.x); // 10
A.prototype = {
x: 20,
y: 30
};
alert(a.y) // undefined
- 为什么它委托(delegate)给
a.x 的旧原型(prototype)
而不是新的 一个? - 为什么
a.y
抛出undefined
是在prototype
中设置的?
最佳答案
发生这种情况是因为当您设置了A.prototype = obj
您没有向 a
继承的 Object 添加属性,而是创建了一个全新的对象作为 A.prototype
而这个不是由 a
考虑一下,
function A() {}
A.prototype.x = 10;
var p1 = A.prototype; // keep reference to this
var a = new A();
A.prototype = {x: 20, y: 30};
Object.getPrototypeOf(a) === A.prototype; // false, not the new prototype
Object.getPrototypeOf(a) === p1; // true, the old prototype
// however
var b = new A();
Object.getPrototypeOf(b) === A.prototype; // true, this is the new prototype
如果您对旧原型(prototype)(我称之为 p1
)的属性进行了更改,这些将被 a
关于javascript - 为什么 a.y 在这里未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428271/