In JavaScript, every object has a prototype. The prototype is a reference to another object that the current object inherits properties and methods from. When you try to access a property or a method on an object, JavaScript first looks for it on that object. If it doesn't find it, it follows the prototype chain, going up the chain of linked objects until it finds the property or method or reaches the end of the chain.
Here's how the prototype chain works:
-
Object Prototypes:
- Every object in JavaScript has a prototype, except for the base object, which is at the top of the prototype chain. The base object has methods and properties that are available to all objects through inheritance.
-
Prototype Linkage:
-
Objects in JavaScript are linked to their prototypes through an internal property called
__proto__
(or [[Prototype
]] in specifications).
-
Objects in JavaScript are linked to their prototypes through an internal property called
-
Accessing Properties and Methods:
-
When you access a property or method on an object, JavaScript first looks for it directly on that object. If it doesn’t find it, it follows the
__proto__
chain, checking the prototype of the current object.
-
When you access a property or method on an object, JavaScript first looks for it directly on that object. If it doesn’t find it, it follows the
-
Chain Traversal:
-
If the property or method isn't found in the immediate prototype, JavaScript continues up the prototype chain, checking the
__proto__
of each linked object until it finds the property/method or reaches the end of the chain (the base object).
-
If the property or method isn't found in the immediate prototype, JavaScript continues up the prototype chain, checking the
// Creating an object
let myObject = {
name: 'Alice'
};
// Adding a property to the prototype of myObject
let myPrototype = {
greet() {
console.log(`Hello, ${this.name}!`);
}
};
// Linking the prototype to myObject
myObject.__proto__ = myPrototype;
// Accessing a property/method
myObject.greet(); // Output: 'Hello, Alice!'
In this example:
-
myObject
has aname
property directly on itself. -
It doesn't have a
greet
method directly, but since it's linked tomyPrototype
via__proto__
, it can access thegreet
method defined inmyPrototype
.
-
Changing the prototype (
__proto__
) of an object dynamically is generally not recommended due to potential side effects and performance implications. -
The
prototype
property is often used in constructor functions to define the prototype of objects created by that constructor function. - JavaScript engines optimize prototype chains for efficient property lookups to improve performance.
- Understanding the prototype chain is crucial for comprehending inheritance and object relationships in JavaScript.