What it the significance of the Javascript constructor property?

前端 未结 6 1005
一生所求
一生所求 2020-11-22 04:23

Trying to bend by head around Javascript\'s take on OO...and, like many others, running into confusion about the constructor property. In particular, the signif

6条回答
  •  耶瑟儿~
    2020-11-22 05:13

    The previous answers here say (in various ways) that the value of the constructor property isn't used by anything in JavaScript itself. That was true when those answers were written, but ES2015 and onward have started using constructor for things.

    The constructor property of the prototype property of a function is meant to point back to the function so that you can ask an object what constructed it. It's set up automatically as part of creating a traditional function object or a class constructor object (details).

    function TraditionalFunction() {
    }
    
    console.log(TraditionalFunction.prototype.constructor === TraditionalFunction); // true
    
    class ExampleClass {
    }
    
    console.log(ExampleClass.prototype.constructor === ExampleClass); // true

    Arrow functions don't have a prototype property, so they don't have prototype.constructor.

    For years the JavaScript specification only said that the constructor property would be there and have that value (a link back to the function) by default. But starting in ES2015, that changed, and various operations in the specification now actually use the constructor property, such as this, this, this, and this.

    So when setting up constructor functions that build inheritance chains, it's best to ensure that the constructor property is referring to the appropriate function. See my answer here for examples, etc.

提交回复
热议问题