Tip 38: Share Methods with Inheritance
In this tip, you’ll learn how to extend classes and call parent methods.
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 FlashCoupon
that has deeper discounts but a shorter time span. To create
that class, simply declare a new class called FlashCoupon
that inherits from the
Coupon
class using the extends
keyword.
Your new FlashCoupon
class inherits all the existing properties and methods.
For example, you can access the price
and the getPriceText()
method.
Get hands-on with 1400+ tech skills courses.