Reputation: 37
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
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
Reputation: 72857
Functionally, there's no difference. The constructor
is optional.
So, if your constructor is empty, you can choose to leave it out:
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