What is inheritance in JavaScript?
Inheritance is a technique that enables objects to acquire properties and methods from other objects. By utilizing this approach, we can promote code reuse and establish relationships among objects, allowing us to form a hierarchy where a child object can leverage the attributes and functionalities of its parent objects.
In basic terms, inheritance allows for the transfer of attributes from a parent class to a child class, enabling the reuse of code and the enhancement of the functionalities already established in a previous implementation.
JavaScript inheritance is a feature that enables the creation of new classes derived from pre-existing classes. This mechanism permits the child class to leverage the properties and methods defined in its parent class.
The extends keyword in JavaScript is utilized to establish a child class derived from a parent class. This functionality enables the child class to inherit all the characteristics and behaviors of its parent class.
There are many ways to achieve inheritance in JavaScript Such as:
- Prototypal inheritance
- Classical inheritance
- Functional inheritance
Prototypal inheritance
When an object derives from the prototype of another object, it can acquire methods and properties from that prototype, as every object possesses a prototype. This prototypal inheritance can be implemented in JavaScript in the following manner:
Example:
function Animal(name){
this.name = name;
}
Animal.prototype.sound = function () {
console.log("Generic Sound");
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.sound = function() {
console.log("Woof! Woof!");
};
const myDog= new Dog("Buddy", "Pitbull");
myDog.sound();
Output:
Woof! Woof!
Classical Inheritance
ECMAScript 6 brought forth the Class keyword, facilitating classical inheritance in a manner akin to that of Java and C++. In this discussion, we will delve into the mechanisms by which classical inheritance can be implemented in JavaScript.
Example:
class automobile {
constructor(name, cc) {
this.name = name;
this.cc = cc;
}
engine() {
console.log(`${this.name}
has ${this.cc} engine`);
}
}
class car extends automobile {
engine() {
console.log(this.name,
"has ", this.cc, "cc engine");
}
}
let cars = new car('Supra',"1998");
cars.engine();
Output:
Supra has 1998 cc engine
Functional inheritance
In JavaScript, it is possible for objects to inherit properties and methods from other objects through the use of function constructors. This approach allows us to create objects and define relationships among them. Let’s explore how we can implement functional inheritance in JavaScript in the following manner:
Constructing overriding
In JavaScript, when we create a subclass, it is often necessary to override the constructor. This can be accomplished by utilizing the super keyword, which serves to call the constructor of the parent class.
Example
function Animal(name) {
const obj = {};
obj.name = name;
obj.sound = function() {
console.log("Some generic sound");
};
return obj;
}
function Cat(name, breed) {
const obj = Animal(name);
obj.breed = breed;
obj.sound = function() {
console.log("Meow Meow!");
};
return obj;
}
const myCat = Cat("Buddy", "Labrador");
myCat.sound();
Output:
Meow Meow!
Points to remember
- It maintains an IS-A relationship.
- The extends keyword is used in class expressions or class declarations.
- Using extends keyword, we can acquire all the properties and behavior of the inbuilt object as well as custom classes.
- We can also use a prototype-based approach to achieve inheritance.
Uses of Inheritance
A child class can derive all the attributes and behaviors from its parent class, enabling us to leverage existing code effectively.
When a feature is created, we can effortlessly inherit its attributes. There is no necessity to create something from scratch. This approach enables us to streamline the code, making it more manageable and easier to maintain.
In the child class, we have the ability to incorporate our functionalities, allowing us to inherit solely the essential properties and methods that characterize the features we need.
By employing inheritance, we have the ability to arrange data in a hierarchical structure.
Through the application of inheritance, we can enhance the code's suitability for debugging.
Advantages of Inheritance in JavaScript
Utilizing inheritance in JavaScript offers various advantages, including:
Reduced Code Duplication
Through the mechanism of inheritance, we enable derived classes to leverage the properties and methods established in the base class, which aids in minimizing code redundancy.
Faster Development
By utilizing pre-existing code, the pace of development can be accelerated since developers are not required to allocate time for testing and crafting code for standard functionalities. This allows them to concentrate on the distinctive features of the derived class, resulting in more efficient workflows and conserving time.
Consistency
It further encourages uniformity across a software application by guaranteeing that every subclass utilizes the identical base class, which results in a consistent collection of properties and methods.
Resource Usage Optimization
By utilizing the current code base, inheritance allows developers to enhance resource efficiency, including CPU cycles and memory consumption, leading to the creation of more effective software applications.
Easier Debugging and Troubleshooting
A well-organized class hierarchy enables developers to swiftly pinpoint issues and address them within the application, as they are already familiar with where the shared functionalities reside. By leveraging inheritance, the processes of debugging and troubleshooting are simplified in such a structured environment.
Scalability
Utilizing this approach enables us to enhance scalability since we can incorporate new classes into the current class hierarchy with ease. The newly created class can derive properties and methods from the base class while also introducing new or distinctive functionalities as required.
In summary, inheritance significantly enhances the efficiency of code reusability, as well as simplifies maintenance and modifications. By establishing a well-organized class hierarchy and leveraging pre-existing code, developers are able to create software applications that are more efficient, uniform, and scalable, while also being easier to maintain and alter.