Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Inheritance

Inheritance lets you build a new class on top of an existing one. The original class is called the parent, and the new one the child. The child gets all the properties and methods of its parent and can add its own or change the inherited ones. This way shared code is written once, and only the differences go into each child.

extends

A child class is declared with the extends keyword:

class Animal {
  constructor(name) {
    this.name = name;
  }
}
 
class Dog extends Animal {}
 
const dog = new Dog('Rex');
 
console.log(dog.name); // Rex

Dog has no constructor of its own — it comes from Animal.

Adding methods

A child can add methods the parent does not have. The inherited ones remain available:

class Animal {
  constructor(name) {
    this.name = name;
  }
 
  describe() {
    return `${this.name} is an animal`;
  }
}
 
class Dog extends Animal {
  bark() {
    return `${this.name}: Woof!`;
  }
}
 
const dog = new Dog('Rex');
 
console.log(dog.describe()); // Rex is an animal
console.log(dog.bark());     // Rex: Woof!

super

If the child needs its own constructor, the first thing it does is call super() — the parent's constructor:

class Animal {
  constructor(name) {
    this.name = name;
  }
}
 
class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
}
 
const dog = new Dog('Rex', 'husky');
 
console.log(dog.name, dog.breed); // Rex husky

Overriding methods

A child may declare a method with the same name — then its version is the one that gets called. The parent's version is called through super:

class Cat {
  sound() {
    return 'Meow';
  }
}
 
class Kitten extends Cat {
  sound() {
    return super.sound() + '-meow';
  }
}
 
console.log(new Kitten().sound()); // Meow-meow

Checking the type

The instanceof operator checks whether an object was created from a class. An object of a child class also counts as an object of the parent:

class Animal {}
class Dog extends Animal {}
 
const dog = new Dog();
 
console.log(dog instanceof Dog);    // true
console.log(dog instanceof Animal); // true

Common mistake

In a child constructor you cannot touch this before calling super() — it throws a ReferenceError:

class Animal {
  constructor(name) {
    this.name = name;
  }
}
 
class Dog extends Animal {
  constructor(name, breed) {
    this.breed = breed;
    super(name);
  }
}
 
try {
  new Dog('Rex', 'husky');
} catch (error) {
  console.log(error.name); // ReferenceError
}

The object is created by the parent's constructor, so before super() it does not exist yet. Call super() first, and only then add your own properties.

Thanks for reading!

Donate to the site — we work hard for you.