Inheriting from a Class: Subclass and Overridden Methods

Learn the syntax and rules to extend a class and override methods in JavaScript's inheritance model.

In the past, to implement prototypal inheritance, you had to literally change the prototype on the constructor function. This was rather inconvenient, error-prone, and not intuitive. Also, there was no clear way to override methods.

This was so hard that most programmers either got it wrong or relied on libraries to do it for them.

Java-like syntax

The updated syntax for inheritance greatly simplifies the task of creating prototypal inheritance. There is also a clear and elegant way to override methods. The syntax for inheritance is much like the one used by other mainstream languages, especially Java. This is good news and bad news.

The good news is that programming inheritance is now very easy and approachable, and the code is easier to understand and maintain.

The bad news, however, is that the syntax is so much like a class-based inheritance. This may lead you to believe that JavaScript supports class-based inheritance. Although the syntax looks like class-based inheritance semantically, under the hood, JavaScript still uses prototypal inheritance, as we discussed in the previous section. Be warned.

To understand how the new inheritance syntax relates to prototypal inheritance, let’s look at some examples.

Extending a class

In the past, we created constructor functions to represent classes and modified their prototype to implement prototypal inheritance. Now, in modern JavaScript, we create classes using the class keyword. Likewise, we implement prototypal inheritance using a different keyword as well.

We need a base class to serve as the prototype and a derived class to reuse the prototype. In short, we need a simple inheritance hierarchy. Let’s first create a class that will serve as the base. We’ll start with a class, Person:

Get hands-on with 1200+ tech skills courses.