Tip 38: Share Methods with Inheritance
Explore how to share methods through inheritance in JavaScript classes. Understand the use of the extends keyword, the super() constructor call, overriding parent methods, and invoking parent methods from child classes to create flexible class hierarchies while managing code clarity and avoiding bloat.
We'll cover the following...
In the previous tip, you learned how to create basic classes with properties and methods. You may recall that classes in JavaScript were highly anticipated and slightly dreaded. The core of the controversy is inheritance.
Inheritance in JavaScript classes
Inheriting methods on prototypes was a pretty complex process in early versions of JavaScript. First, you had to loop through the properties on an object; then, you had to check to see that each property existed specifically on an object as a property and not on the object prototype. Then you had to copy the prototype from the parent to a new object before adding further methods.
It was hard.
With classes, inheritance is easy. Still, in recent years, JavaScript developers have soured on inheritance. They argue that too much inheritance is a bad thing and that it leads to bloated code. There are other techniques for sharing methods that don’t require inheritance (such as composition). In other words, use inheritance with caution.
Example: Inheritance
How does inheritance work? Return to your Coupon class. Suppose you want
a ...