I was playing around with prototypical inheritance, and bumped into something I found a bit remarkable. Here is the case:
function Parent(){
this.name = "parent";
this.age = 30;
};
var parent = new Parent();
console.log(parent.constructor); //Prints function Parent();
function Child(){
this.name = "child";
this.age = 10;
};
var child = new Child();
console.log(child.constructor); //prints function Child()
Child.prototype = new Parent(); //Set inheritance
console.log(Child.prototype.constructor); //prints function Parent() as expected
var child_2 = new Child();
console.log(child_2.constructor); //prints function Parent() ??
console.log(child_2.name); //Yet prints child, meaning the child's constructor is still function Child()
Although I am not surprised that the constructor of Child
is function Parent()
after the inheritance is defined, I am a bit surprised that the constructor of child_2
is function Parent()
, because the property set in the constructor body of Child
, ie.
this.name = "child"
Is still executed.
Is there a practical reason behind this occurrence?