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
-
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; } }
-
Define some methods in that “class”.
'use strict'; class Animal { constructor(color) { this._color = color; } ... makeSound() { console.log('Generic animal cannot make any sound.'); } }
-
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; } }
-
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; } }
-
Optional: overwrite some methods in the “subclass”.
... class Dog extends Animal { ... makeSound() { console.log('Wuff wuff'); } }
-
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
- Use prototypical inheritance, which is more natural to the language JavaScript.
- In ES5: use pure pseudoclassical inheritance