//1)
function Rabbit() {}
Rabbit.prototype = {
eats: true
};
let rabbit = new Rabbit();
Rabbit.prototype = {};
alert( rabbit.eats ); // true
//2)
function Rabbit() {}
Rabbit.prototype = {
eats: true
};
let rabbit = new Rabbit();
Rabbit.prototype.eats = false;
alert( rabbit.eats ); // false
I expected ‘false’ in the 1) case..and contemplated about this mechanism and conclude something on my own. please see if I am right 🙂
Here’s what happens:
1)
I define a Rabbit constructor function and set its prototype to an object with an eats property set to true.
I create a new instance of Rabbit using the new keyword and store it in the rabbit variable.
After that, I change the Rabbit.prototype to an empty object. However, this change does not affect the already created rabbit object.
When I try to access rabbit.eats, JavaScript first looks for the eats property directly on the rabbit object. Since the eats property is not found on the rabbit object, it goes up the prototype chain and finds it on the old prototype object { eats: true }. As a result, the alert shows true.
2)
the alert shows false.
In this case, I am modifying the eats property directly on the same object that the rabbit object points to through its [[Prototype]] link. So, the change is visible when accessing rabbit.eats.
Q)
I learned that objects assignning give varibles the address which is called object reference.
case 2) was easy to understand according to this. but I expected ‘false’ in the case 1).
My conclusion)
when I created ‘Rabbit’ function, the ‘Rabbit.prototype’ object is assigned to a memory. and in the case 2) ‘Rabbit’ and ‘rabbit functions share the same memory address however, in the case 1), when I assign ‘{}’ to the ‘Rabbit.prototype’property. they find new memory address and assign this to it so the first object and second object that assigned to ‘Rabbit.prototype’ have diffrent memory address so that Rabbit.prototype refer to new memory address and rabbit.eats refere to old one.
Am I right?


