For every class definition written, there needs to be at least one specific method; that is the constructor
method. Furthermore, this should be the first method defined.
The constructor method is always called by JavaScript when creating a new object from a class. Therefore you must have a constructor method. You can think about it as; “JavaScript must ‘construct’ or build a new object. The constructor method is how a new object gets built.”
JavaScript uses the constructor method to build new objects of a class type. Although you have not seen how to instantiate a new object from a class yet, you need to accept, that the constructor method is called by JavaScript.
The constructor method should be used to setup or initialize an object’s properties.
As an example, if we were creating a digital car, we may want to specify properties such as;
color
make
model
year
You will learn more specifically how to do this on the next page.
As mentioned, the constructor method should be the first method in a class definition.
Furthermore, if there is data that needs to be shared with the newly created object, this should be represented as input parameters to this function.
Roughly, this may look like;
// a class definition
class ClassName {
// constructor method
constructor( inputParameter1, inputParameter2 ) {
// method function block
// Do stuff here to create an object
console.log(inputParemeter1);
}
}