Implementing a Constructor

You know how to create a class, but you haven’t seen how to define the body of the constructor. Creating a class defines a no-parameter default constructor, which appears to be empty bodied. But you may want to execute some code as part of object construction. For that we need to define an explicit constructor. That’s exactly what we’ll do next.

Let’s first examine the default constructor that is automatically created when you define a class.

 class​ Car {}
 
 console.log(Reflect.ownKeys(Car.prototype));

We created a class named Car, with a default constructor. Then, using the Reflect class’s ownKeys() method, we examine the properties of the Car’s prototype—you’ll learn about Reflect in Chapter 12, Deep Dive into Metaprogramming. This reveals the default constructor that JavaScript quietly created for us:

 [ 'constructor' ]

We may provide an implementation or body for the constructor if we like. For that, we’ll implement a special method named constructor in the class, like so:

 class​ Car {
 constructor​(year) {
 this​.year = year;
  }
 }
 
 console.log(​new​ Car(2018));

The constructor may take zero, one, two, or any number of parameters, including default and rest parameters. The body of the constructor may initialize fields, like this.year in the example, and may perform actions. The output of the previous code shows that the constructor initialized the this.year field:

 Car { year: 2018 }

A constructor is called when an instance is created using the new keyword. The constructor can’t be called directly without new, as we saw earlier. If you do not have anything useful to do when an object is created, then do not implement a constructor—the default constructor is sufficient. If you want to initialize some fields or perform some actions when an instance is created, then write a constructor. However, keep the constructor short and the execution fast—you don’t want to slow down during creation of objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset