What is the prototype chain and how does it work?
TL;DR
The prototype chain is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. When you try to access a property on an object, JavaScript will first look for the property on the object itself. If it doesn't find it, it will look at the object's prototype, and then the prototype's prototype, and so on, until it either finds the property or reaches the end of the chain, which is null
.
In this example, alice
inherits the greet
method from Person.prototype
.
What is the prototype chain and how does it work?
Understanding prototypes
In JavaScript, every object has a prototype. A prototype is also an object, and it can have its own prototype, forming a chain. This chain is known as the prototype chain.
How the prototype chain works
When you try to access a property or method on an object, JavaScript will:
- Look for the property or method on the object itself.
- If it doesn't find it, it will look at the object's prototype.
- If it still doesn't find it, it will look at the prototype's prototype.
- This process continues until it either finds the property or method or reaches the end of the chain, which is
null
.
Example
In this example:
alice
is an instance ofPerson
.alice
does not have agreet
method directly on it.- JavaScript looks at
alice
's prototype, which isPerson.prototype
. Person.prototype
has agreet
method, so JavaScript calls it.
Prototype chain in built-in objects
JavaScript's built-in objects also use the prototype chain. For example, arrays inherit from Array.prototype
, which in turn inherits from Object.prototype
.
In this example:
arr
is an instance ofArray
.arr
does not have atoString
method directly on it.- JavaScript looks at
arr
's prototype, which isArray.prototype
. Array.prototype
has atoString
method, so JavaScript calls it.
Modifying prototypes
You can add properties and methods to an object's prototype, and all instances of that object will have access to those properties and methods.
In this example, we added a sayGoodbye
method to Person.prototype
, and now alice
can use it.