Why isn't this allowed before super()

前端 未结 3 1043
春和景丽
春和景丽 2020-12-31 09:34

I have been coding in React js. I have read that in ES6 classes to access \'this\' we need to first call super(props) and I would like to know why this is.Answers I have fou

3条回答
  •  被撕碎了的回忆
    2020-12-31 09:56

    The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of a parent class.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

    It means if you have class MyComponent extends React.Component you always need super() call in order to make this defined.

    If you don't specify a constructor method, a default constructor is used.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor#Default_constructors

    Constructor of superclass should be called before this in order to finish configuration of this before subclass started configuration of this. Otherwise superclass constructor could get this modified by subclass. Superclass should not know something about subclasses. That is why super() call in constructor should be before access to this.

提交回复
热议问题