为什么在super()之前不允许这样做 [英] Why isn't this allowed before super()

查看:76
本文介绍了为什么在super()之前不允许这样做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用React js进行编码。我已经读过在ES6课程中访问'this'我们需要先调用super(道具),我想知道为什么这是。答案我发现主要是谈论Javascript无法知道'这个'是什么,除非超类叫做。我想知道这是什么意思,因为在构造函数之外,'this'被识别,我们每次都不会调用super(props)。

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 found mainly talk about Javascript being unable to know what 'this' is unless superclass is called. I would like to know what that means because outside the constructor, 'this' is recognized and we don't call super(props) each time.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}


推荐答案


构造函数方法是一种用于创建和初始化使用类创建的对象的特殊方法。在类中只能有一个名为constructor的特殊方法。如果类包含多个构造函数方法,则将抛出SyntaxError。构造函数可以使用super关键字来调用父类的构造函数。

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 ()调用以便进行此定义。

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

超级类的构造函数应该在 this 之前调用,以便完成的配置在子类开始配置这个之前。否则,超类构造函数可以获得由子类修改的。超类不应该知道关于子类的东西。这就是为什么构造函数中的 super()调用应该在访问之前

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.

这篇关于为什么在super()之前不允许这样做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆