Inheritance in JavaScript
Inheritance in JavaScript allows one class to acquire the properties and methods of another class. This helps in reusing code, reducing duplication, and organizing programs in a clear and logical way.
The extends keyword is used to create a child class that inherits from
a parent class. The super() method is used inside the child class to
call the constructor of the parent class.
Example: Car and Model Classes
In this example, the Car class is the parent class, and the Model class is the child class that inherits from it.
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand); // Call the parent constructor
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
const myCar = new Model("Ford", "Mustang");
Explanation
1. Parent Class (Car)
The Car class defines a constructor that stores the car brand and a
method called present() that returns a message describing the car.
2. Child Class (Model)
The Model class uses the extends keyword to inherit from
the Car class. This means it automatically gains access to the
carname property and the present() method.
3. Using super()
The super(brand) statement calls the constructor of the parent class.
This ensures that the inherited properties are properly initialized before adding
new properties in the child class.
4. Child Method
The show() method belongs only to the child class. It combines the
parent method present() with the model name to create a complete
message.
Output
Why Use Inheritance?
- Encourages code reuse
- Makes programs easier to maintain
- Represents real-world relationships
- Improves code organization