2Minutes: Prototype Chain In JavaScript
Prototype Chain is one of the most important concepts in JavaScript. Understanding it helps us understand how JavaScript looks up properties and methods behind the scenes.
Before we dive in, there’s one concept we should remember: everything in JavaScript has a prototype, and even primitive values can access methods because JavaScript temporarily wraps them in their corresponding object types.
Number.prototype = {
toString() { ... },
valueOf() { ... },
toFixed() { ... },
// ...
__proto__: Object.prototype
}Although age is a primitive number (not a Number object), JavaScript temporarily creates a Number object so it can look up the toString() method on Number.prototype. After the method finishes, that temporary object is discarded.
This is how a Number object looks like internally:
Number.prototype = {
toString() { ... },
valueOf() { ... },
toFixed() { ... },
// ...
__proto__: Object.prototype
}And Number.prototype looks roughly like:
Number.prototype = {
toString() { ... },
valueOf() { ... },
toFixed() { ... },
// ...
__proto__: Object.prototype
}Notice that even a Number object has a __proto__ that points to Number.prototype. Number.prototype itself has a __proto__ that points to Object.prototype, which contains methods inherited by all objects. In general, when JavaScript can’t find a property or method on an object, it follows the prototype chain until it finds it or reaches null.
What is Prototype Chain?
Looking back at our Number example, JavaScript looks for toString() on the Number object first. If it can’t find it there, it follows the __proto__ link to Number.prototype. If it’s still not found, it continues to Object.prototype. Finally, Object.prototype.__proto__ is null, which marks the end of the prototype chain.
This process of following __proto__ links until JavaScript finds a property or reaches null is called the Prototype Chain.
The same concept applies to everything in JavaScript. Open your browser’s DevTools (F12), create objects of different types, and inspect their __proto__ chains to see how JavaScript resolves properties and methods.
That’s 2Minutes, see you in the next one !
Sources
JavaScript Enlightement (book): https://www.amazon.com/JavaScript-Enlightenment-Library-User-Developer/dp/1449342884
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain