Changing "prototype"
In the code below we create new Rabbit, and then try to modify its prototype.
In the start, we have this code:
function Rabbit() {}
Rabbit.prototype = {
eats: true
};
let rabbit = new Rabbit();
alert( rabbit.eats ); // true
-
We added one more string (emphasized). What will
alertshow now?function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); Rabbit.prototype = {}; alert( rabbit.eats ); // ? -
…And if the code is like this (replaced one line)?
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); Rabbit.prototype.eats = false; alert( rabbit.eats ); // ? -
And like this (replaced one line)?
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); delete rabbit.eats; alert( rabbit.eats ); // ? -
The last variant:
function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); delete Rabbit.prototype.eats; alert( rabbit.eats ); // ?
Answers:
-
true.The assignment to
Rabbit.prototypesets up[[Prototype]]for new objects, but it does not affect the existing ones. -
false.Objects are assigned by reference. The object from
Rabbit.prototypeis not duplicated, it’s still a single object referenced both byRabbit.prototypeand by the[[Prototype]]ofrabbit.So when we change its content through one reference, it is visible through the other one.
-
true.All
deleteoperations are applied directly to the object. Heredelete rabbit.eatstries to removeeatsproperty fromrabbit, but it doesn’t have it. So the operation won’t have any effect. -
undefined.The property
eatsis deleted from the prototype, it doesn’t exist any more.