[JavaScript – ES2015] Class – Inheritance

JavaScript classes can also be inherited from another class. So that it can “extends” the functionality.

 

1. Inheritance

Inheritance in Object-Oriented Programming establishes the “is-a” relationship. The keyword “extends” is used in JavaScript. In JavaScript, all objects are inherited from “Object“.

class Person {
  constructor() {
    this._name = "";
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
}

class Employee extends Person {
}

let emp = new Employee();
emp.name = "Homer";
console.log(emp.name); // Homer

The code is primitive but can be a starting point. Let’s improve step by step.

 

2. super

One way to access the super (base) class members is to use the “super“.

The most frequently used pattern is to call the constructors of the base class. Let’s add another field “department” in the child class.

class Person {
  constructor(name) {
    this._name = name;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
}

class Employee extends Person {
  constructor(name, department) {
    super(name);
    this._department = department;
  }
  get department() {
    return this._department; // readonly
  }
}

let emp = new Employee("Homer", "Sales");
console.log(`${emp.department}: ${emp.name}`);

 

3. Overrides Methods

Methods can be more interesting in the hierarchy chain.

  • Methods are inherited to the child (derived) classes
  • The “super” keyword is used to call the base class’s members
  • You can override the method by redefining it in the child class
class Animal {
  move() {
    return "Run";
  }
}

class Cat extends Animal {
}

class Dog extends Animal {
  move() {
    return super.move() + " fast";
  }
}

class Bird extends Animal {
  move() {
    return "Fly";
  }
}

let cat = new Cat();
let dog = new Dog();
let bird = new Bird();
console.log(cat.move()); // Run
console.log(dog.move()); // Run fast
console.log(bird.move()); // Fly

This simple example clearly shows how methods can be inherited or overridden.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s