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 ); // ? -
Lultima variante:
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); delete Rabbit.prototype.eats; alert( rabbit.eats ); // ?
Riposte:
-
true.Lassegnazione a
Rabbit.prototypeimposta[[Prototype]]per i nuovi oggetti, ma non influenza gli oggetti gi esistenti. -
false.Gli oggetti vengono assegnati per riferimento. Loggetto 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 laltro.
-
true.Tutte le operazion di
deletevengono applicate direttamente alloggetto. Quidelete rabbit.eatsprova a rimuovere la proprieteatsdarabbit, ma non esiste. Quindi loperazione non avr alcun effetto. -
undefined.La propriet
eatsviene rimossa da prototype, non esiste pi.