Prototype Chain:
The prototype chain is a fundamental concept in JavaScript used to establish the inheritance relationship between objects. It consists of a series of links where each object has a reference to its prototype, which is another object from which it can inherit properties and methods. This chain continues from one object to the next until it reaches null, which is the prototype of Object.prototype, marking the end of the chain.
How Objects Inherit Properties and Methods:
- Property Access:
- When you attempt to access a property or a method on an object, JavaScript first checks if that property/method is directly on the object itself.
- Chain Lookup:
- If the property/method isn't directly on the object, JavaScript then checks the object’s prototype, which is accessible via the
__proto__property (deprecated) orObject.getPrototypeOf()method. It looks to see if the property/method exists there. - Continuing Up the Chain:
- If the property/method is not found on the prototype, the search moves up to the prototype’s prototype, and so on, traversing up the prototype chain.
- End of the Chain:
- The search continues until the property/method is found or until it reaches Object.prototype. If the property/method is not found even on Object.prototype, JavaScript returns undefined.
- Object.prototype's prototype is null, signaling the end of the prototype chain.
Demo Examples:
// Example demonstrating prototype chain function Animal(name) { this.name = name; } // Adding a method to the Animal prototypeAnimal.prototype.sayName = function() {
console.log('My name is ’ + this.name);
};
// Creating an instance of Animal
let cat = new Animal(‘Fluffy’);
// Accessing a property directly on the object
console.log(cat.name); // Output: Fluffy
// Accessing a method, JavaScript checks the prototype chain
cat.sayName(); // Output: My name is Fluffy
// Example demonstrating prototype chain lookup
let dog = {
breed: ‘Labrador’
};
// Adding a property directly to the dog object
dog.age = 3;
// Accessing properties and methods, JavaScript traverses the prototype chain
console.log(dog.breed); // Output: Labrador
console.log(dog.age); // Output: 3
console.log(dog.toString()); // Output: [object Object]
In the above examples:
- The first example defines a constructor function Animal and adds a method sayName to its prototype. Instances of Animal (like cat) inherit this method through the prototype chain.
- The second example demonstrates prototype chain lookup with a plain JavaScript object dog. Properties and methods can be accessed directly on the object or inherited through the prototype chain.