Normally when we create a new object using "new" keyword, actually the __proto__ property of the created object is pointing to the prototype property of the parent class. We can test this as below :
function myfunc(){};
myfunc.prototype.name="myfunction";
var child= new myfunc();
child.__proto__=== myfunc.prototype ---> true
But let's see what happens when I change the prototype of the parent function:
myfunc.prototype={};
child.__proto__=== myfunc.prototype ---> false
child.name ------> "myfunction"
So if child.__proto__ isn't pointing to the myfunc.prototype, so where it is pointing in objects chain? More important if it doesn't point to the myfunc.prototype, then how it has access to the "name" property of myfunc class?
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
.