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:
In this example, Circle extends Shape, meaning it inherits Shape's properties and methods, and at the same time providing methods of its own. Note that Circle does not define its own constructor. In JavaScript, derived classes without an explicit constructor automatically call super() with the same arguments passed to the derived class constructor.
Overriding Methods
Derived classes can override methods of their base classes to provide behavior specific to the subclass.
Here, Circle overrides the print method to reflect its specific type.
Calling Parent Methods with super
You can also call a parent class's method from within the derived class using super.methodName(). This is useful when you want to extend the parent's behavior rather than completely replace it.
Here, super.print() executes the parent's logic before adding the subclass-specific output.
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:
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
In JavaScript class inheritance, which statements are true?