Ad space (banner)
🟨JavaScript Lessons
Lesson 17 / 69

Inheritance (Extending Classes)

In this lesson you'll learn class inheritance in JavaScript using extends, so you can efficiently design classes that share common functionality. This is for people searching "JavaScript extends usage" or "JavaScript class inheritance."

Using extends lets you create a new class that inherits the functionality of an existing class. This is called inheritance. You can call the parent class's constructor processing with super(). Picture it like this: starting from a shared blueprint called "Animal," you add each animal's own way of making a sound — "Dog," "Cat," and so on. Grouping shared parts into a parent class saves you from writing the same code over and over.

The sample code inherits from the Animal class to create a Dog class. The Dog class redefines its own speak() method, which is called "overriding." An instance created with new Dog("Rex") has both the name property inherited from Animal and the Dog-specific speak().

A common beginner stumbling block is forgetting to call super() inside the child class's constructor. If you define your own constructor in an inherited class, you must call super() before using this, to run the parent class's initialization — forgetting this causes an error. Also watch out: as the inheritance chain gets deeper, the design gets more complicated.

In real development, inheritance is used when you want to share common functionality while changing just some behavior — for example, inheriting a "base button" to create a "submit-only button" or a "delete-only button." It's a representative technique of object-oriented design, and an important idea even in the design of large applications.

Rather than completely overriding a parent class's method, if you want to keep the parent's processing and add extra processing on top, you can call the parent class's method from within the child class's method using super.speak().

While inheritance is convenient, if the relationship between parent and child classes gets too complicated, it can actually make the code harder to read. Carefully thinking through "should this be inheritance, or should these just be separate classes?" at the design stage is also an important skill in real projects.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)