Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, is constructor mandatory in a class?

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.

like image 408
Andrew Lam Avatar asked Feb 07 '18 06:02

Andrew Lam


People also ask

Is it mandatory for a class to have a constructor?

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.

Why do we need constructors in JavaScript class?

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.

What happens if you do not add a constructor to a class?

If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.


2 Answers

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); } 
like image 134
Suresh Atta Avatar answered Sep 27 '22 21:09

Suresh Atta


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() } 
like image 38
Pramod Kumar Avatar answered Sep 27 '22 22:09

Pramod Kumar