Logo

Developer learning path

JavaScript

Inheritance in JavaScript

Inheritance

51

#description

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

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.