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ù.