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 theprototype
of the function.At this point
is referring to the object
So, when you do
internally
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 namemyfunc.prototype
. Now, bothchild.__proto__ === myfunc.prototype
and are referring to{ name: 'myfunction' }
. That is whychild.__proto__ === myfunc.prototype
is returningtrue
.Now, when you do
you are making
myfunc.prototype
refer the new object{}
, but thechild.__proto__
is still referring to the old object{ name: 'myfunction' }
. That is whychild.__proto__ === myfunc.prototype
returnsfalse
andchild.name
still saysmyfunction
.