微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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()应该在访问它之前.

原文地址:https://www.jb51.cc/js/150483.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐