我一直在React js编码.我已经读过在ES6课程中访问’this’我们需要先调用super(道具),我想知道为什么这是.答案我发现主要是谈论
Javascript无法知道’这’是什么,除非超类叫做.我想知道这是什么意思,因为在构造函数之外,’this’被识别,我们每次都不调用super(props).
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state */ }; } }
解决方法
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
这意味着如果你的类MyComponent扩展了React.Component,你总是需要调用super()来定义它.
If you don’t specify a constructor method,a default constructor is used.
应该在此之前调用超类的构造函数,以便在子类开始配置之前完成此配置.否则超类构造函数可以通过子类修改它.超类不应该知道关于子类的东西.这就是为什么在构造函数中调用super()应该在访问它之前.