0

In object-oriented languages like C++ you don't have to call the base constructor. I don't understand why I need to do it in a psuedo object-oriented language like javascript. My base constructor has virtual elements that need to be setup before I call it. Constructors worked fine in ES5, why ruin them with this restriction. This error is garbage, it should be removed.

Nick Sotiros
  • 2,194
  • 1
  • 22
  • 18

1 Answers1

0

In C++ the compiler creates code to call the base constructor for you before your derived class constructor is called. Your C++ derived class definition can specify which base constructor to call and what to pass it (if there is a choice). That's how the C++ specification is written. See short explanation here.

Javascript ES6 classes do not work the exact same way. You have to insert a place in your code where the base constructor is called with super(...) and you can specify or compute the parameters to pass to the base constructor.

In both C++ and Javascript, you can't access your own instance methods or properties before the base constructor has been called.

FYI, Java is even more restrictive than Javascript. You must put a call to super() or this() as the first statement of your constructor. Javascript at least lets you put logic that doesn't use this before calling the constructor.


In your Javascript, you can't stop this error without rewriting your code to work a different way. It's not an error you can disable.

There are valid OOP reasons (whether you agree with them or not) to not allow references to an object until all base classes have been fully initialized. Or, you can go back to the pre-ES6 way of initializing objects where there are no controls on how you do things and you can do whatever you want.

If you show us your code and explain what you're trying to do, we can likely suggest a different design that solves your problem and does not have this issue.

jfriend00
  • 683,504
  • 96
  • 985
  • 979