Wierd behaviour of constructor property of an object

前端 未结 2 453
离开以前
离开以前 2021-01-26 06:37

In the following code, why is \'scotty.constructor\' set to \'Dog\' function ? How is the constructor property of an object set in general ? Is it set to the function that creat

2条回答
  •  耶瑟儿~
    2021-01-26 07:10

    Object don't have an own constructor property, it's taken from their protos. So, without this line:

    ShowDog.prototype = new Dog();
    

    the inheritance diagram would be

    Once you assign new Dog to the prototype (thus discarding its current value), the picture becomes:

    and the constructor value (Dog) is taken from scotty.__proto__.__proto__

    To make inheritance work as intended, you have to assign the constructor manually:

    ShowDog.prototype = new Dog()
    ShowDog.prototype.constructor = ShowDog
    

    which yields the following diagram:

提交回复
热议问题