我什么时候需要从构造函数中调用`super`? [英] When do I need to call `super` from a constructor?

查看:534
本文介绍了我什么时候需要从构造函数中调用`super`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读博士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...


  1. 我需要从构造函数中访问 this

  2. 超类构造函数需要不同的参数,然后是派生类构造函数

还有其他时候我应该包含对超类构造函数的调用吗?

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 returning an object, which you hardly ever would.

这篇关于我什么时候需要从构造函数中调用`super`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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