Classes in ES2015/ES6

  2 mins read  

Classes in ES2015/ES6

The ES2015 Language Specification ushered in much needed improvements for OO patterns in JavaScript. New syntactic sugar provides JavaScript with features that have been available in most popular programming languages (e.g. Java, C#, Scala, Ruby). Programming errors should be reduced by the simplified syntax and reduction in cognitive dissonance.

Declaration

car {
}

Construction

A single constructor method is used for the creation and initialization of a class. The example below creates an instance of the Car class and initializes the cylinder and speed properties.

class Car {
  constructor(cylinders) {
    this.cylinders = cylinders;
    this.speed = 0;
  }
}

Methods

Methods can be introduced to a class by declaring a function inside the class declaration. The following example adds an increaseSpeed method to the Car class.

class Car {
  ...
  increaseSpeed() {
    this.speed += 1;
  }
}

var car = new Car();
car.increaseSpeed();

Inheritance

A class can be derived from another class. This allows properties and methods to be inherited from the base class. The following FastCar class subclasses the Car class and calls the inherited increaseSpeed method.

class FastCar extends Car {
  constructor() {
    super(6);
  }
}

var fastCar = new FastCar();
fastCar.increaseSpeed();

Method Overriding

Methods can easily be overridden, allowing a class to redefine the behavior of the base class’s method. Below the increaseSpeed method is overridden and increments the speed with a larger value than the base Car class.

class FastCar extends Car {
  ...
  increaseSpeed() {
    this.speed += 3;
  }
}

Static Methods

Static methods can be added to a class by using the static keyword. Static methods can be called on a class that has not been instantiated.

class Car {
  ...
  static pressHorn() {
    return 'beep';
  }
}

var sound = Car.pressHorn();
console.log(sound); // beep

Future

Classes defined by ES2015 Language Specification are not supported by any major browser. However, this doesn’t mean applications cannot be developed using classes. Trans-compilers such as Babel can be used to compile ES2015 code to ES5 compatible code, allowing developers to support legacy browsers and develop for evergreen browsers.

CODE SAMPLES The ES105 example and ES5 class examples can be found on GitHub. Please feel free to fork and improve the project. Thanks.