Search code examples
javascriptconstructorprototypeundefinedsuperclass

Javascript using constructor.prototype to visit superclass member fails?


I've got a small code snippet:

function father(){
    this.id=10
}
function child(){}
console.log(child.prototype.constructor);//[Function: child]
child.prototype=new father();
//child.prototype.constructor = child; // key line
var son=new child();
console.log(child.prototype.constructor);//[Function: father]
console.log(son.constructor.prototype.id);//undefined.

As the code indicates, I used prototype chain to create "son" object. But The last line prints

"undefined". 

This is weird to me. child.prototype.constructor is [Function: father], and "id" is actually a property of "father" why it prints undefined?

If I uncomment the keyline of

    child.prototype.constructor = child; // key line

Then it prints "10" as I expected. The difference of having the key line or not, for me, is child.prototype.constructor is either 'child' or 'father'. But 'id' is a father property, why need to set key line in my code?

Thanks.


Solution

  • Step 1)

    function father(){
        this.id=10
    }
    function child(){}
    

    Looks like

    enter image description here

    and this case when do console.log(child.prototype.constructor);//[Function: child] it works as you expected

    STEP 2) child.prototype=new father();

    enter image description here

    Now you see here, original child.prototype is lost and child.prototype.constructor is also lost. you created an object from father and used that object as child.prototype

    STEP 3) var son=new child();

    enter image description here

    Now console.log(child.prototype.constructor);//[Function: father] is straight forward to understand.

    How do we get there ? son.__proto__.__proto__.constructor.

    Now, considering the same image

    console.log(son.constructor.prototype.id);//undefined. What happens here ? son.constructor is nothing but father and son.constructor.prototype is nothing but father.prototype , which does not have a property names id.

    NOTE: son.constructor is son.__proto__.__proto__.constructor

    Now what happens you uncomment child.prototype.constructor = child; ?

    You are adding a constructor property to child.prototype and in that case when you say son.constructor this means child and son.constructor.prototype is nothing but child.prototype , which does have a property names id and value is 10.

    Sorry for all images and bad explanation!!