ES6 – Classes – Inheritance

In the previous blog ES6 – Classes I showed how the ES6 class syntax can make the Javascript classes look like C# classes for example and where the restrictions are. In this blog I will show what class inheritance features ES6 has.

Base and Derived Classes

In the example below we have a base class called Animal and a derived class called Cat.

class Animal {

}

class Cat Extends Animal{

}

We instantiate the class as we do for any class.

let _cat = new Cat();

Calling a Method in the Base Class

In the Animal class we create a Sound method that is not in the Cat class.

class Animal {
   Sound() {
      return "Some animal noise";
   }
}

When we call the Sound method from the Cat class instance, since the Cat class does not have a Sound method, it calls the Sound method from the Animal class.

_cat.Sound(); // Returns: "Some animal noise"

Calling a Method in the Derived Class

We have now added a Sound method to the Cat class.

class Cat {
   Sound() {
      return "Meow!!!";
   }
}

When we call the Sound method from the Cat class instance, it calls the Sound method from the Cat class. This is the equivalent of method overrides on C#.

_cat.Sound(); // Returns: "Meow!!!"

Calling a Setter and Getter in the Base Class

With Setters and Getters, the property is held in the base class.

get Name() {
   return this._name;
}

set Name(value) {
   if (value) {
      this._name = value;
   }
}

We use them no different to any other class.

_cat.Name = "tibbles";
_cat.Name; // Returns: "tibbles"

Calling a Base Class Member

We are often required to access members of a base class from a derived class. We can access method, Properties and Constructors of the base class. In the Animal class we have a method Legs.

Legs() {
   return "4";
}

In the Cat class we also have a method called Legs but we call the base class version and then append some details. Notice we user the super keyword. C# for example; uses the keyword Base.

Legs() {
   return super.Legs() + " Legs";
}

When we call the Cat class Legs method we get the following output. This is a contrived example however; this is often done in the real world to extend base class behaviour rather than override.

_cat.Legs(); // Returns: "4 Legs"

Calling a Base Constructor

We can also call the base class constructor which is often used to initialise base class properties. In the Animal class we initialise the Name property in the constructor.

constructor(name) {
   this._name = name;
}

In the Cat class we also include the Name property however; since the property only exists in the base class, we call the Animal constructor passing in the value. Notice we call super as a method.

constructor(name) {
   super(name);
}

When we instantiate the Cat class and look at the Name property, the value is returned.

let _cat = new Cat("tibbles");
_cat.Name; //Returns: "tibbles"

So that’s it for ES6 class inheritance functionality. Hope it was useful.