user11844995
user11844995

Reputation: 37

What if we omit constructor in JS

I am new in JS and was learning classes and constructor that is put inside class but I wonder what happens behind the scenes if we omit constructor inside class. For example,

class UI{

this.box = document.querySelector(".box");
this.footer = document.querySelector(".footer");

render(){
.......
}

}

Is the above code equivalent to

class UI{

constructor(){}

this.box = document.querySelector(".box");
this.footer = document.querySelector(".footer");

render(){
.......
}

}

Thus if we omit constructor then we won't be able to access variables box and footer in newly created instances of UI. Is that right?

Upvotes: 0

Views: 1231

Answers (2)

cmaderthaner
cmaderthaner

Reputation: 447

If you omit the constructor, an implicit default constructor is used. The default constructor looks exactly like the one in your example.

For more thorough information look at the MDN web docs.

Upvotes: 2

Cerbrus
Cerbrus

Reputation: 72857

Functionally, there's no difference. The constructor is optional.

So, if your constructor is empty, you can choose to leave it out:

enter image description here

Note how the left variant doesn't specify a constructor, but still has one. That's the default constructor, for when no constuctor has been specified:

constructor() {}

For derived classes, the default constructor is different:

constructor(...args) {
  super(...args);
}

Upvotes: 2

Related Questions