Neues Node.js-Buch
Alle Artikel

Apply ES2015 class inheritance

Problem

You want to apply inheritance using the class syntax introduced in ES2015.

Ingredients

  • 2 or more “classes”
  • the extends keyword
  • the super keyword

Directions

  1. Define a “class”. Optionally define some properties, getter and setters.

    'use strict';
    class Animal {
      constructor(color) {
       this._color = color;
      }
      get color() {
        return this._color;
      }
      set color(color) {
        this._color = color;
      }
    }
  1. Define some methods in that “class”.

    'use strict';
    class Animal {
      constructor(color) {
       this._color = color;
      }
      ...
      makeSound() {
        console.log('Generic animal cannot make any sound.');
      }
    }
  2. Define another “class” as “subclass” using the extends keyword. Optionally defined some properties, getters and setters.

    ...
    class Dog extends Animal {
      constructor(name, color) {
        this._name = name;
      }
      get name() {
        return this._name;
      }
      set name(name) {
        this._name = name;
      }
    }
  3. Call the super constructor using super(), passing the parameters expected by the super constructor.

    ...
    class Dog extends Animal {
      constructor(name, color) {
        super(color);
        this._name = name;
      }
      get name() {
        return this._name;
      }
      set name(name) {
        this._name = name;
      }
    }
  4. Optional: overwrite some methods in the “subclass”.

    ...
    class Dog extends Animal {
      ...
      makeSound() {
        console.log('Wuff wuff');
      }
    }
  5. Voilá, there you got a perfect, tasteful ES2015 inheritance.

    'use strict';
    class Animal {
      constructor(color) {
       this._color = color;
      }
      get color() {
        return this._color;
      }
      set color(color) {
        this._color = color;
      }
      makeSound() {
        console.log('Generic animal cannot make any sound.');
      }
    }
    class Dog extends Animal {
      constructor(name, color) {
        super(color);
        this._name = name;
      }
      get name() {
        return this._name;
      }
      set name(name) {
        this._name = name;
      }
      makeSound() {
        console.log('Wuff wuff');
      }
    }
    let dog = new Dog('Bello', 'brown');
    console.log(dog.name);                 // "Bello"
    console.log(dog.color);                // "brown"
    console.log(dog instanceof Dog);       // true
    console.log(dog instanceof Animal);    // true
    dog.makeSound();                       // "Wuff wuff"
    let animal = new Animal('yellow');
    console.log(animal.color);             // "yellow"
    console.log(animal instanceof Animal); // true
    console.log(animal instanceof Dog);    // false
    animal.makeSound();                    // "Generic animal cannot make any sound."

Alternative recipes