I am reading about JavaScript class from the Mozilla documentation section of 'Class body and method definitions'. Under the Constructor section, it states that
The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of the super class.
From the statement above, I can confirm that we can't have more than one constructor. But it does not mention whether a constructor is mandatory in a class declaration/expression in JavaScript.
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.
You should just write a class without a constructor and see if it works :)
From the same docs
As stated, if you do not specify a constructor method a default constructor is used. For base classes the default constructor is:
constructor() {}
For derived classes, the default constructor is:
constructor(...args) { super(...args); }
No, It is not necessary. By default constructor is defined as :
constructor() {}
For inheritance we use this constructor to call super class as :
constructor() { super.call() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With