JavaScript - Prototypes and Prototype Chain in JavaScript
In JavaScript, every object has an internal property called prototype. The prototype is another object from which the current object can inherit properties and methods. This is the basis of inheritance in JavaScript.
When a property or method is accessed on an object, JavaScript first checks whether that property exists in the object itself. If it is not found, JavaScript looks for it in the object's prototype. This searching process continues through a chain of prototypes until the property is found or the end of the chain is reached. This sequence is called the prototype chain.
The prototype mechanism allows objects to share properties and methods. Instead of each object having its own copy of a method, the method can be defined in the prototype so that all objects created from that prototype can use it. This helps save memory and keeps code organized.
For example, when a function is used as a constructor, JavaScript automatically creates a prototype object for that function. Properties and methods added to this prototype can be accessed by all objects created using that constructor.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return "Hello " + this.name;
};
let p1 = new Person("Ravi");
console.log(p1.greet());
In this example, the object p1 does not have the greet method directly. JavaScript finds it in Person.prototype through the prototype chain.
The prototype chain continues until it reaches Object.prototype, which is the top-level prototype in JavaScript. If the property is not found there, the result is undefined.
Understanding prototypes and the prototype chain is important because it explains how inheritance works in JavaScript and how objects share functionality efficiently.