Inheritance allows new classes (or constructor functions) to be created based on existing classes. This enables the child class to reuse methods and properties from a parent class, providing flexibility and code reuse.
// Parent class
function Vehicle(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
// Method shared by all vehicles
Vehicle.prototype.info = function() {
console.log("This is a " + this.year + " " + this.make + " " + this.model);
};
// Child class inheriting from Vehicle
function Car(make, model, year, color) {
Vehicle.call(this, make, model, year); // Call parent constructor
this.color = color;
}
// Inherit methods from Vehicle
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
// Additional method for Car class
Car.prototype.drive = function() {
console.log("Driving the " + this.color + " " + this.make + " " + this.model);
};
// Create instances
var myCar = new Car("Renault", "Kwid", 2024, "blue");
var anotherCar = new Car("Honda", "Civic", 2023, "red");
// Call methods
myCar.info(); // Outputs: "This is a 2024 Renault Kwid"
myCar.drive(); // Outputs: "Driving the blue Renault Kwid"
anotherCar.info(); // Outputs: "This is a 2023 Honda Civic"
anotherCar.drive(); // Outputs: "Driving the red Honda Civic"
The extends keyword is used to create a child class based on a parent class. This keyword facilitates the child class in inheriting all the properties and behavior (methods) of its parent class.
// Using extend keyword
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // Call the constructor of the Parent class
this.age = age;
}
introduce() {
console.log(`My name is ${this.name} and I am ${this.age} years old.`);
}
}
const child = new Child("Rajesh", 10);
child.greet(); // Outputs: "Hello, Rajesh!"
child.introduce(); // Outputs: "My name is Alice and I am 10 years old."