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

前端 未结 2 1202
萌比男神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条回答
  •  旧时难觅i
    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.

提交回复
热议问题