Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...