我什么时候需要从构造函数中调用`super`? [英] When do I need to call `super` from a constructor?
问题描述
阅读博士Axel Rauschmayer关于ES6课程的博客,我知道派生类在没有提供时会有以下默认构造函数
Reading Dr. Axel Rauschmayer's blog on ES6 classes, I understand that a derived class has the following default constructor when none is provided
constructor(...args) {
super(...args);
}
我也明白,如果我想使用这个
在构造函数中我首先需要调用 super
,否则此
将不会被初始化(抛出一个ReferenceError)。
I also understand that if I want to use this
within a constructor I first need to call super
, otherwise this
will not yet be initialized (throwing a ReferenceError).
constructor(width, height) {
this.width = width; // ReferenceError
super(width, height);
this.height = height; // no error thrown
...
}
以下假设然后纠正? (如果没有,请你解释我应该明确调用 super
的条件)
Is the following assumption then correct? (and if not, could you please explain the conditions under which I should explicitly call super
)
对于派生类,我只需要明确地调用 super
...
For derived classes, I only need to explicitly call super
when...
- 我需要从构造函数中访问
this
- 超类构造函数需要不同的参数,然后是派生类构造函数
还有其他时候我应该包含对超类构造函数的调用吗?
Are there other times when I should include a call to the superclass constructor?
推荐答案
是的,这听起来很正确,虽然有点奇怪。规则应该是
Yes, that sounds correct, albeit a bit oddly formulated. The rules should be
- 在派生类中,总是 1 需要调用
super(...)
构造函数 - 如果你做的不是默认构造函数,你可以省略整个
constructor(){}
,
这反过来会使你的类代码不包含超级调用。
- In a derived class, you always1 need to call the
super(…)
constructor - If you are not doing more than the default constructor, you can omit the whole
constructor(){}
, which in turn will make your class code not contain a super call.
1:你不需要在明确的返回
一个对象的可疑边缘情况下调用它,你几乎不会。
1: You don't need to call it in the suspicious edge case of explicitly return
ing an object, which you hardly ever would.
这篇关于我什么时候需要从构造函数中调用`super`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!