且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 20:18:58


构造函数方法是一种用于创建和初始化使用类创建的对象的特殊方法。在类中只能有一个名为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.