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:
Prototype: Every JavaScript object has a hidden property called
__proto__
(or simplyprototype
for built-in objects). This points to another object, which acts as its "prototype."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.
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:
Explanation:
Animal
is a function that acts as a constructor for creating animal objects.Animal.prototype
holds thespeak
method, which is inherited by all instances ofAnimal
.When you create
dog
, it gets its properties (name
) from the instance itself and thespeak
method fromAnimal.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