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

前端 未结 2 1201
萌比男神i
萌比男神i 2020-12-16 07:49

Reading Dr. Axel Rauschmayer\'s blog on ES6 classes, I understand that a derived class has the following default constructor when none is provided

constructo         


        
相关标签:
2条回答
  • 2020-12-16 08:48

    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.

    0 讨论(0)
  • 2020-12-16 08:55

    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.

    0 讨论(0)
提交回复
热议问题