the javascript object model: strange constructor property

前端 未结 2 471
太阳男子
太阳男子 2021-01-06 04:16

I find the behaviour of this piece of code puzzling, why is the constructor of child not Child? Can someone please explain this to me?



        
相关标签:
2条回答
  • 2021-01-06 05:07

    As Pointy has pointed out, in his answer

    The "constructor" property is a reference to the function that created the object's prototype, not the object itself.

    The usual way to deal with this is to augment the object's prototype constructor property after assigning to the prototype

    function Parent() {
        this.prop1 = "value1";
        this.prop2 = "value2";
    }
    
    function Child() {
        this.prop1 = "value1b";
        this.prop3 = "value3";
    }
    Child.prototype = new Parent();
    
    // set the constructor to point to Child function
    Child.prototype.constructor = Child;
    
    var child = new Child();
    
    // this is expected
    console.log(child instanceof Child); //true
    console.log(child instanceof Parent); //true
    
    // corrected
    console.log(child.constructor == Child); // now true
    console.log(child.constructor == Parent); // now false
    
    console.log(Child.prototype.constructor); // Child
    console.log(Parent.prototype.constructor); // Parent
    

    I can't recommend Stoyan Stefanov's Object Oriented JavaScript enough which covers Prototype and Inheritance in some detail (get the second edition if you can as it addresses some critiques of the first edition).

    0 讨论(0)
  • 2021-01-06 05:14

    The "constructor" property is a reference to the function that created the object's prototype, not the object itself.

    0 讨论(0)
提交回复
热议问题