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
alert
show 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.prototype
sets up[[Prototype]]
for new objects, but it does not affect the existing ones. -
false
.Objects are assigned by reference. The object from
Rabbit.prototype
is not duplicated, it’s still a single object referenced both byRabbit.prototype
and by the[[Prototype]]
ofrabbit
.So when we change its content through one reference, it is visible through the other one.
-
true
.All
delete
operations are applied directly to the object. Heredelete rabbit.eats
tries to removeeats
property fromrabbit
, but it doesn’t have it. So the operation won’t have any effect. -
undefined
.The property
eats
is deleted from the prototype, it doesn’t exist any more.