Defining Class Members

When creating abstractions, we often arrive at methods that may not be specific to any particular instance. Sometimes they are general and sometimes they may deal with multiple instances. A class method, instead of an instance method, is used to design these.

JavaScript makes it easy to define static methods and static properties. It does not, however, provide an elegant way to define static fields. Let’s continue with our Car class to add a few static members.

First, let’s add a static field to the class. For this, we have to step out of the class definition, like so:

 Car.distanceFactor = 0.01; ​//This goes outside class Car {...}

We may also define property getters (and setters if we like), and those go within the class with the static prefix. For example, let’s define an ageFactor property as a class member:

 static​ ​get​ ageFactor() { ​return​ 0.1; }

Except for the static prefix, there’s no difference between how we define an instance property getter and a class property getter. Of course, the class property getters and setters will not have implicit access to any instance properties, fields, or methods.

The keyword this within static getters, static setters, and static methods is dynamically scoped—it does not refer to the instance of the class. When a static member is called on a class, this refers to the class, but if this is bound to some other object by the caller, then this may refer to something other than the class.

Finally, let’s define a static method in the Car class:

 static​ pickBetter(carA, carB) {
 const​ computeScore = car =>
  car.age * Car.ageFactor + car.distanceTraveled * Car.distanceFactor;
 
 return​ computeScore(carA) < computeScore(carB) ? carA : carB;
 }

The pickBetter() method is marked as static but it looks much like an instance method otherwise. While we may use this to refer to the static members, it is safer to use the class name, like Car.ageFactor, instead of this.ageFactor—this will prevent us from issues with this referring to something other than the class at runtime due to dynamic scoping.

Let’s take a look at calling the static method of the class.

 const​ car1 = ​new​ Car(2007);
 car1.drive(150000);
 
 const​ car2 = ​new​ Car(2010);
 car2.drive(175000);
 
 console.log(Car.pickBetter(car1, car2));

Instead of calling on any particular instance, we call pickBetter() using the class name. Instance methods can’t be called using the class reference and static methods can’t be called using an instance reference.

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

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