JavaScript(JS) Inheritance

Inheritance is a powerful concept in object-oriented programming that allows objects to inherit properties and methods from their parent objects. In JavaScript, inheritance is implemented using prototypal inheritance.

In prototypal inheritance, each object has an internal property called [[Prototype]] that refers to its parent object. When a property or method is accessed on an object, JavaScript first looks for the property or method on the object itself. If it doesn't find it, it looks for it on the object's [[Prototype]] property. This process continues until the property or method is found or the end of the prototype chain is reached.

Here is an example of how prototypal inheritance works in JavaScript:

// Define a parent object
const person = {
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

// Define a child object that inherits from the parent object
const student = Object.create(person);
student.study = function() {
  console.log(`${this.name} is studying for a test.`);
};

// Create an instance of the child object
const john = Object.create(student);
john.name = "John";

john.greet(); // output: "Hello, my name is John"
john.study(); // output: "John is studying for a test."
Source‮ww:‬w.theitroad.com

In this example, we first define a parent object called person with a method greet. We then create a child object called student using the Object.create method, which sets the [[Prototype]] property of the student object to the person object. We also define a method study on the student object.

We then create an instance of the student object called john and set its name property to "John". When we call the greet method on the john object, JavaScript first looks for the method on the john object itself and doesn't find it, so it looks for it on the [[Prototype]] property, which is the student object. Since the student object doesn't have a greet method either, JavaScript looks for it on the [[Prototype]] property, which is the person object. It finds the greet method on the person object and executes it.

Similarly, when we call the study method on the john object, JavaScript looks for the method on the john object itself and finds it, so it executes it.

This example demonstrates how inheritance works in JavaScript using the prototypal inheritance mechanism. By defining objects with a [[Prototype]] property that refers to their parent object, we can create a hierarchy of objects with shared properties and methods.