Where The __proto__ Is Pointing When We Change The Prototype Of The Parent Object?
Solution 1:
When you are using new operator to create an Object, a new JavaScript Object will be created and its internal __proto__ property will be set to the prototype of the function.
At this point
console.log(myfunc.prototype);
is referring to the object
{ name: 'myfunction' }
So, when you do
var child = new myfunc();
internally
child.__proto__ = myfunc.prototype;is happening. Now, the important thing to understand here is, in JavaScript, when you use assignment operator, the left hand side name will be just made to refer the result of the right hand side expression. So, in this case, child.__proto__ is just another name for the object referred by the name myfunc.prototype. Now, both child.__proto__ === myfunc.prototype and are referring to { name: 'myfunction' }. That is why child.__proto__ === myfunc.prototype is returning true.
Now, when you do
myfunc.prototype = {};you are making myfunc.prototype refer the new object {}, but the child.__proto__ is still referring to the old object { name: 'myfunction' }. That is why child.__proto__ === myfunc.prototype returns false and child.name still says myfunction.
Post a Comment for "Where The __proto__ Is Pointing When We Change The Prototype Of The Parent Object?"