Prototype Chains
Every object has a prototype, and that prototype can in turn have its own prototype. This creates a linked list called the Prototype Chain.
This chain goes all the way back to the root Object.prototype, whose own prototype is always null (marking the end of the chain).
Traversing the Chain
When you try to access a property or method on an object, JavaScript engine executes a specific lookup sequence:
- It checks if the property exists directly on the object itself.
- If it doesn’t, it checks the object’s prototype.
- If it doesn’t find it there, it checks the prototype’s prototype.
- It continues up the chain until it either finds the property or hits
null. If it hitsnull, it returnsundefined.
Inspecting Prototypes
You can view the exact prototype of any object using the built-in Object.getPrototypeOf() method.
const pureTitan = { name: "Eren's mom" };
// Create a child object
const beastTitan = Object.create(pureTitan);
beastTitan.name = "Zeke";
console.log(beastTitan);
// Output: { name: "Zeke" }
console.log(Object.getPrototypeOf(beastTitan));
// Output: { name: "Eren's mom" } (This is pureTitan)
console.log(Object.getPrototypeOf(Object.getPrototypeOf(beastTitan)));
// Output: {} (This is the global Object.prototype)
console.log(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(beastTitan))));
// Output: null (End of the chain)
A Common Misconception
A common misunderstanding is that using Object.create() copies the properties from the parent directly into the child object. It does not.
The child object remains completely empty until you explicitly add properties to it. It only appears to have properties because JavaScript secretly falls back to the parent object when you ask for a property the child doesn’t physically possess.