A
A
antpv2018-05-14 20:12:39
JavaScript
antpv, 2018-05-14 20:12:39

Why does this code work the way it does?

I understand correctly? When a rabbit is created, will its __proto__ be set to a reference to the Rabbit.prototype object?

function Rabbit() {}
Rabbit.prototype = {
  eats: true
};

var rabbit = new Rabbit();

Rabbit.prototype = {}; //*

alert( rabbit.eats );

Why does the alert output true when overwriting this object with an empty object? because __proto__ refers to an already empty object
function Rabbit(name) {}
Rabbit.prototype = {
  eats: true
};

var rabbit = new Rabbit();

Rabbit.prototype.eats = false;

alert( rabbit.eats );

And at this point, we just change the property of the object that __proto__ rabbit refers to, and everything works as it should. (outputs false)
So what's the difference?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2018-05-14
@antpv

Why does the alert output true when overwriting this object with an empty object? because __proto__ refers to an already empty object

When creating an object via a constructor, the object reference is copied from prototype to __proto__. In this code, it turns out that rabbit __proto__ is equal to the object reference { eats: true }, it no longer depends on Rabbit.prototype. But if you create the object again through the constructor, then its __proto__ will be equal to {}
Yes, because both __proto__ and prototype refer to the same object, so it's clearer.
var obj = {
  eats: true
}
function Rabbit(name) {}
Rabbit.prototype = obj 

var rabbit = new Rabbit();

alert(Rabbit.prototype == obj); // true 
alert(rabbit.__proto__ == obj); // true
alert(rabbit.__proto__ == Rabbit.prototype); // true, т.к. у обоих ссылка на один и тот же объект.

Even if you write obj = null, you simply remove the reference to the object { eats: true } from the obj variable, but the object itself remains, and other references to it also remain.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question