0

What is prototype chaining and how does inheritance work in JavaScript?

author
kallyani
medium
0
23

Answer

In JavaScript, prototype chaining is the way objects inherit features from other objects. Every object has a hidden property called [[Prototype]] (or __proto__), which points to another object — its prototype.

When you try to access a property on an object:

  • JavaScript first looks for the property on that object itself.
  • If it’s not found, it moves up the prototype chain and checks the object’s prototype.
  • This continues until it reaches the end of the chain (null).

This is how inheritance works in JavaScript — objects can share and reuse properties and methods through their prototypes.


function Person(name) {
this.name = name;
}

Person.prototype.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};

const user = new Person("abcd");
user.greet(); // Output: Hello, I'm abcd


Here, user doesn’t have the greet method directly.
JavaScript looks up the prototype chain and finds it in Person.prototype.


In short: Prototype chaining allows objects to inherit properties and methods, making JavaScript’s inheritance system flexible and efficient.

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0
    What is prototype chaining and how does inheritance work in JavaScript? - prototype | EBAT