Inheritance in JavaScript
Inheritance
51
Inheritance in JavaScript refers to the process of creating new objects based on existing objects. It is a way to establish a relationship between two or more objects where one object acquires the properties and methods of another object.
In JavaScript, inheritance is achieved through the prototype chain. Every object has a prototype object, which is a reference to another object from which the current object inherits its properties and methods. When a property or method is accessed on the current object, JavaScript first looks for it on the object itself. If it is not found there, it searches for it on the prototype of the object. If it is still not found, it keeps searching up the prototype chain until it reaches the top, which is the Object.prototype.
To create a new object that inherits from an existing object, you can use the object.create() method. This method creates a new object with the given prototype object.
Here is an example:
// Parent object var person = { firstName: "", lastName: "", fullName: function() { return this.firstName + " " + this.lastName; } }; // Child object var student = Object.create(person); student.firstName = "John"; student.lastName = "Doe"; console.log(student.fullName()); // "John Doe"
In this example, we create a parent object person
with properties firstName
, lastName
, and method fullName
. Then we create a child object student
that inherits from the person
object using the Object.create()
method. We set the firstName
and lastName
properties on the student
object and call the fullName()
method on it, which returns the full name of the student.
March 25, 2023