Writing classes in ES6
July 16, 2017 Leave a comment
ES6 has introduced classes and object inheritance. These are welcome additions since they provide a more convenient way to build object-oriented code than before with functions and prototypes.
Unsurprisingly the keyword to build a class is “class”. Here’s the most simple class with a default empty constructor:
class Animal { }
Where is the constructor? If you only need an empty constructor then you don’t need to add it to the class. This reflects the behaviour we see in all mainstream OO languages like Java or C#. If you want you can add a constructor with the “constructor” keyword:
class Animal { constructor() { } }
However, that goes against the ES6 specifications. If you have an ESLint code style checker plugged into your JS compilation process then it might complain saying that is a useless constructor, depending on the JS style rules. Here’s an example for how ESLint might give you the bad news after loading your JS project in a web browser:
Here’s the Animal class with two properties, name and age, and two functions, makeSound and move:
class Animal { constructor(options) { this.name = options.name this.age = options.age } makeSound() { return 'WHOOAAA' } move() { console.log('I\'m moving forward') } }
We can construct a new Animal with the “new” keyword and then call its properties and functions:
let myAnimal = new Animal({name: 'Simba', age: 10}) let age = myAnimal.age let name = myAnimal.name let sound = myAnimal.makeSound() myAnimal.move()
So now we want to extend the Animal class with specialised classes like Cat or Dog. ES6 has the “extends” and “super” keywords that also seem very familiar especially to Java developers. Here’s a Dog class:
class Dog extends Animal { constructor(options) { super(options) this.type = options.type } makeSound() { return 'WOOFFF' } getMyBestFriend() { return "cat" } }
In the Dog constructor we first call the constructor of the base class. Then there’s also a custom property called type. The Dog class overrides the makeSound() function, silently inherits the move function from Animal and also introduces a new function getMyBestFriend. Here’s how we can instantiate and use a Dog object:
let myDog = new Dog({name: 'Fluffy', age: 5, type: 'Shepherd'}) myDog.age myDog.name myDog.type myDog.makeSound() myDog.getMyBestFriend()
myDog.makeSound() will return WOOFFF and not WHOOAAA since it was overridden.
View all posts related to JavaScript here.