javascript – 为什么在super()之前不允许这样做

我一直在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.

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

应该在此之前调用超类的构造函数,以便在子类开始配置之前完成此配置.否则超类构造函数可以通过子类修改它.超类不应该知道关于子类的东西.这就是为什么在构造函数调用super()应该在访问它之前.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...