...

/

Tip 38: Share Methods with Inheritance

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 ...

Access this course and 1400+ top-rated courses and projects.