Question 41

Question

Explain the prototype chain in JavaScript.

Answer

Imagine a Family Tree:

Think of an object like a person, and each object inherits characteristics (properties and methods) from its "parent" object. The prototype chain is like a family tree where objects are connected through prototypes.

Key Points:

  1. Prototype: Every JavaScript object has a hidden property called __proto__ (or simply prototype for built-in objects). This points to another object, which acts as its "prototype."

  2. Inheritance: An object inherits properties and methods from its prototype. If an object doesn't have a specific property, it looks up the prototype chain to see if any parent object has it.

  3. Chain Reaction: The prototype itself can also have a prototype, creating a chain! This continues until you reach Object.prototype, which is at the very top of the chain for all objects.

Example:

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

Animal.prototype.speak = function() {
  console.log(`${this.name} makes a sound!`);
};

const dog = new Animal("Buddy"); 
// 'dog' object inherits from 'Animal' prototype

dog.speak(); // Outputs: "Buddy makes a sound!"

Explanation:

  • Animal is a function that acts as a constructor for creating animal objects.

  • Animal.prototype holds the speak method, which is inherited by all instances of Animal.

  • When you create dog, it gets its properties (name) from the instance itself and the speak method from Animal.prototype.

Practical Significance:

  • Code Reusability: Define methods once in a prototype and reuse them across many objects, saving space and effort.

  • Extensibility: Easily add new properties or methods to existing prototypes without modifying original objects.

Last updated