Inheritance is an important concept in Object-Oriented Programming (OOP). In JavaScript, inheritance is achieved using the prototype object, which allows one object to access properties and methods of another object.
Inheritance allows one class or object to acquire properties and methods from another class or object.
It helps in code reusability and reduces duplication.
JavaScript supports inheritance through prototype objects.
This technique is commonly known as Prototypal Inheritance or Behavior Delegation.
Let's create a Person class with FirstName and LastName properties.
Methods can be added to the prototype object so that all instances can access them.
Prototype methods are shared among all objects created from the constructor.
Amit Kumar
Suppose we want a Student class that inherits all properties and methods of Person.
This avoids rewriting FirstName, LastName, and getFullName().
JavaScript does not support multiple inheritance directly like some other programming languages.
However, similar functionality can be achieved using mixins and object composition.
A child object or class can override methods of its parent by creating a method with the same name.
The child's method will be executed instead of the parent's method.
The this keyword always refers to the current object instance.
It works correctly in both parent and child objects.
The Object.create() method creates a new object using an existing object as its prototype.
This is one of the most common ways to implement inheritance.
When JavaScript cannot find a property in an object, it searches the object's prototype.
If not found there, it continues searching through the prototype chain.
JavaScript follows this chain until the requested property or method is found.
| Concept | Description |
|---|---|
| Prototype | Object used for inheritance |
| Object.create() | Creates object with specified prototype |
| Prototype Chain | Search path for properties and methods |
| Method Overriding | Replacing parent method in child |
A Student can inherit properties like Name and Age from Person.
The Student class can also add its own properties such as Roll Number, Course, or Marks.
Which object is mainly used to implement inheritance in JavaScript?