When do I need to call `super` from a constructor?

别说谁变了你拦得住时间么 提交于 2019-11-27 19:00:20

问题


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);
}

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
    ...
}

Is the following assumption then correct? (and if not, could you please explain the conditions under which I should explicitly call super)

For derived classes, I only need to explicitly call super when...

  1. I need to access this from within the constructor
  2. The superclass constructor requires different arguments then the derived class constructor

Are there other times when I should include a call to the superclass constructor?


回答1:


Yes, that sounds correct, albeit a bit oddly formulated. The rules should be

  • 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: You don't need to call it in the suspicious edge case of explicitly returning an object, which you hardly ever would.




回答2:


You need to call super in a subclass constructor in these cases:

  • You want to reference this in the subclass constructor
  • You don't return a different object in the subclass constructor

In other cases, you can call it if you want the superclass constructor to run, but you don't have to.

class SuperClass{
  constructor() {
    console.log('SuperClass');
  }
}
class SubClass1 extends SuperClass {
  constructor() {
    console.log('SubClass1');
    super();
    return {};
  }
}
class SubClass2 extends SuperClass {
  constructor() {
    console.log('SubClass2');
    return {};
  }
}
new SubClass1();
new SubClass2();

I don't see how the order of arguments matters when deciding whether you should call super or not.



来源:https://stackoverflow.com/questions/41350931/when-do-i-need-to-call-super-from-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!