JavaScript: Class Inheritance

Introduction to JavaScript Class Inheritance

Class inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and methods from another class. In JavaScript, class inheritance is implemented using the extends keyword, providing a way to create a class as a derived class that inherits from a base class.

For more information about the basic syntax, see JavaScript: Classes and Basic Syntax.

Creating a Derived Class

To create a class that inherits from another, we use the extends keyword:

class Shape { constructor(color) { this.color = color; } getColor() { return this.color; } } class Circle extends Shape { setRadius(number) { console.log('radius set to ' + number); } } const circle = new Circle('yellow'); console.log(circle.getColor()); circle.setRadius(20);

In this example, Circle extends Shape, meaning it inherits Shape's properties and methods, and at the same time providing methods of it's own.

Overriding Methods

Derived classes can override methods of their base classes to provide behavior specific to the subclass.

class Shape { print() { console.log('I am a Shape'); } } class Circle extends Shape { print() { console.log('I am a Square'); } } const shape = new Shape(); const circle = new Circle(); shape.print(); circle.print();

Here, Circle overrides the print method to reflect its specific type.

Accessing Parent Constructor: super keyword

When a class extends another class, the constructor function of the derived class needs to call the parent's constructor using super() before it can use this. Here’s how super is used in constructors to ensure the parent class is initialized:

class Polygon { constructor(height, width) { this.name = 'Polygon'; this.height = height; this.width = width; } } class Square extends Polygon { constructor(length) { super(length, length); // Calls the parent class's constructor with height and width this.name = 'Square'; } print() { console.log(`name: ${this.name}, length: ${this.height}`) } } const square = new Square(4); square.print();

Summary

JavaScript class inheritance is a powerful feature that allows for the creation of a more manageable and hierarchical object model. By understanding and using inheritance effectively, you can write more organized and modular JavaScript code. Inheritance not only promotes code reuse but also helps in creating an intuitive relationship between components in your application.

Practice Your Knowledge

In JavaScript class inheritance, which statements are true?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?