Inheritance in JavaScript
In this tutorial, we will learn about inheritance in JavaScript.
Inheritance is one of the four fundamental OOP concepts. It is the mechanism by which one class acquires the properties and behavior of another class. It allows a class to inherit properties and behavior from another class.
JavaScript supports inheritance through prototype-based inheritance. In prototype-based inheritance, objects can inherit properties and behavior from other objects. Every object in JavaScript has a prototype object that it inherits properties and behavior from.
Example
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function () {
return this.name;
};
function Employee(name, age, salary) {
Person.call(this, name, age);
this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.getSalary = function () {
return this.salary;
};
let employee = new Employee("John", 25, 50000);
console.log(employee.name); // John
console.log(employee.age); // 25
console.log(employee.salary); // 50000
console.log(employee.getName()); // John
console.log(employee.getSalary()); // 50000In the above example, the Person class is the base class, and the Employee class is the derived class. The Employee class inherits properties and behavior from the Person class using prototype-based inheritance.
Conclusion
- Inheritance is the mechanism by which one class acquires the properties and behavior of another class.
- JavaScript supports inheritance through prototype-based inheritance.
- In prototype-based inheritance, objects can inherit properties and behavior from other objects.
- Every object in JavaScript has a prototype object that it inherits properties and behavior from.
- Inheritance allows a class to inherit properties and behavior from another class.
- Inheritance is used to create a hierarchy of classes where one class is a subclass of another class.
- Inheritance is used to reuse code and to create a relationship between classes.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on