Cambiare "prototype"
Nel codice sotto, andiamo a creare new Rabbit, e successivamente proviamo a modificare il suo prototype.
Inizialmente, abbiamo questo codice:
function Rabbit() {}
Rabbit.prototype = {
eats: true
};
let rabbit = new Rabbit();
alert( rabbit.eats ); // true
-
Aggiungiamo una o più stringhe. Cosa mostrerà
alertora?function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); Rabbit.prototype = {}; alert( rabbit.eats ); // ? -
…E se il codice è come il seguente (abbiamo rimpiazzato una sola riga)?
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); Rabbit.prototype.eats = false; alert( rabbit.eats ); // ? -
E in questo caso (abbiamo rimpiazzato solo una riga)?
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); delete rabbit.eats; alert( rabbit.eats ); // ? -
L’ultima variante:
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); delete Rabbit.prototype.eats; alert( rabbit.eats ); // ?
Riposte:
-
true.L’assegnazione a
Rabbit.prototypeimposta[[Prototype]]per i nuovi oggetti, ma non influenza gli oggetti già esistenti. -
false.Gli oggetti vengono assegnati per riferimento. L’oggetto in
Rabbit.prototypenon viene duplicato, è sempre un oggetto riferito sia daRabbit.prototypeche da[[Prototype]]dirabbit.Quindi quando cambiamo il suo contenuto tramite un riferimento, questo sarà visibile anche attraverso l’altro.
-
true.Tutte le operazion di
deletevengono applicate direttamente all’oggetto. Quidelete rabbit.eatsprova a rimuovere la proprietàeatsdarabbit, ma non esiste. Quindi l’operazione non avrà alcun effetto. -
undefined.La proprietà
eatsviene rimossa da prototype, non esiste più.