Perché è delegare al vecchio prototipo di a.x e non quella più recente? Perché il lancio di un.y non definito attraverso di esso è impostato in prototipo?
È stato creato un tutto new prototype object
. gli oggetti creati già prima della modifica della proprietà del prototipo avranno il vecchio riferimento e il nuovo objects
avrà il nuovo 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
La regola generale è, prototype
è impostato al momento della creazione dell'oggetto e in seguito non si può cambiare. È possibile aggiungere o modificare nuove proprietà esistenti di object’s prototype
.
Tuttavia, è possibile eseguire una soluzione con la proprietà __proto__
.
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);
Perché 'a' è stato creato dal vecchio prototipo. È collegato all'oggetto prototipo, non a 'A', quindi l'assegnazione non cambia nulla. Vedi anche [here] (https://stackoverflow.com/questions/14568239/javascriptinstanceof-operator) o [there] (https: // stackoverflow.it/questions/17474390/defining-a-javascript-prototype) – Bergi