Inheriting from a Class: Subclass and Overridden Methods
Explore how to use modern JavaScript class inheritance with extends and super to create subclasses. Learn to override methods and properties properly, understand the relationship between JavaScript's prototypal inheritance and class-based syntax, and use this and super to access members correctly.
We'll cover the following...
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 ...