JavaScript Class Inheritance
Subject: JavaScript
Class inheritance in JavaScript allows one class (child/subclass) to inherit properties and methods from another class (parent/superclass). It uses the extends and super keywords and is essential for object-oriented programming.
Why Use Class Inheritance?
- Code reusability: Share methods and properties between related classes.
- Maintainability: Avoid code duplication.
- Extensibility: Add or override child class behavior.
Syntax
Example 1: Simple Inheritance
- Dog inherits makeSound() from Animal.
- Dog has its own method bark().
Example 2: Using super() in Constructor
Overriding Parent Methods
Child classes can override inherited methods:
Calling Parent Methods Inside Overridden Methods
Use super.methodName() to call a parent’s method:
Key Takeaways
- Use
extendsto inherit from another class. super()calls the parent constructor and methods.- Inheritance promotes code reuse, structure, and extensibility.
- Child classes can override or extend parent behavior.