Why does it delegate to old prototype of a.x and not the newer one?
Why is a.y throwing undefined through it is set in prototype?
You have created an entirely new prototype object
. objects created already before the prototype property was changed will have the old reference and new objects
will have new prototype
.
// was before changing of A.prototype
a.[[Prototype]] ----> Prototype <---- A.prototype
// became after
A.prototype ----> New prototype // new objects will have this prototype
a.[[Prototype]] ----> Prototype // it will still reference to old prototype
The thumb rule is, prototype
is set the moment of object's creation and later on you cannot change. It is possible only to add new or modify existing properties of the object’s prototype
.
However, you can make a workaround with __proto__
property.
function A() {}
A.prototype.x = 10;
var a = new A();
alert(a.x); // 10
var _newPrototype = {
x: 20,
y: 30
};
A.prototype = _newPrototype; //will fail
alert(a.y) // undefined
A.__proto__ = _newPrototype; //will work
alert(a.x);
alert(a.y);