JavaScript, how to extend a class

By

Learn how to extend a class in JavaScript with the extends keyword, so a subclass like Fish inherits methods from a base Animal class and adds its own.

~~~

To extend a class in JavaScript you use the extends keyword. The new class inherits all the methods of the class it extends, and can add its own.

This is how inheritance works with JavaScript classes.

Suppose you have a class Animal:

class Animal {
  breathe() {
    //...
  }
}

All animals breathe. I think. We can take this as a general rule for this example.

But not all animals walk. Some animals can fly, etc.

So we can extend this class to form species, and we extend from the base class to inherit the breathe() method, and provide specific methods and properties:

class Fish extends Animal {
  swim() {
    //...
  }
}
class Bird extends Animal {
  fly() {
    //...
  }
}

You can instantiate an instance of a class using the new keyword, and you end up with an object:

const randomAnimal = new Animal()
const hummingbird = new Bird()

Now hummingbird can call both fly(), defined on Bird, and breathe(), inherited from Animal. That’s the whole point of extending: you write the shared behavior once, in the base class.

What about constructors?

Things get a bit more interesting when the classes have constructors.

If the subclass defines its own constructor, it must call super() before touching this. Calling super() runs the parent constructor:

class Animal {
  constructor(name) {
    this.name = name
  }
}

class Bird extends Animal {
  constructor(name, wingspan) {
    super(name)
    this.wingspan = wingspan
  }
}

const hummingbird = new Bird('hummingbird', 8)
hummingbird.name //'hummingbird'

If the subclass has no constructor at all, you don’t need to do anything. JavaScript calls the parent constructor for you, passing along the arguments.

Overriding a method

A subclass can also redefine a method it inherited. Define a method with the same name, and the subclass version wins:

class Fish extends Animal {
  breathe() {
    //breathe through gills
  }
}

Inside the new method, you can still call the parent version with super.breathe(), if you need to run it as part of the new behavior.

A common error

Be careful with the order inside the constructor. If you access this before calling super(), JavaScript throws:

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

The fix is to make super() the first thing in the subclass constructor, before any this.something = value assignment.

~~~

Related posts about js: