Classes

JavaScript did not have classes at all before they were added to the language specification in 2015 but allowed for object-oriented programming using Prototypes-based inheritance. And even though a class keyword is available nowadays, JavaScript is still a prototype-based language.

Class Declarations

With the new syntax, classes are defined with the class keyword, followed by the name of the class and the class body in curly brackets. The body contains the definition of the constructor function, i.e. a special method with the name constructor. This function works just like the constructor function in the prototype syntax. The class body also contains all method definitions. The syntax for the methods is similar to the shorthand notation we have seen for adding functions as values inside an object, see Concept Objects.

class Car {
  constructor(color, weight) {
    this.color = color;
    this.weight = weight;
    this.engineRunning = false;
  }

  startEngine() {
    this.engineRunning = true;
  }

  addGas(litre) {
    // ...
  }
}

const myCar = new Car();
myCar.startEngine();
myCar.engineRunning;
// => true

Keep in mind that behind the scenes, JavaScript is still a prototype-based language. All the mechanisms we learned about in the "Prototype Syntax" section above still apply.

Private Fields, Getters and Setters

By default, all instance fields are public in JavaScript. They can be directly accessed and assigned to.

However, there is an established convention that fields and methods that start with an underscore should be treated as private. They should never be accessed directly from outside the class.

Private fields are sometimes accompanied by getters and setters. With the keywords get and set you can define functions that are executed when a property with the same name as the function is accessed or assigned to.

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

  get mileage() {
    return this._mileage;
  }

  set mileage(value) {
    throw new Error(`Mileage cannot be manipulated, ${value} is ignored.`);
    // Just an example, usually you would not provide a setter in this case.
  }
}

const myCar = new Car();
myCar.mileage;
// => 0
myCar.mileage = 100;
// => Error: Mileage cannot be manipulated, 100 is ignored.

References


Children
  1. Inheritance