Chapter 6 Cheatsheet: Prototypes
This cheatsheet summarizes the mechanics of Prototypal Inheritance in JavaScript covered in Chapter 6.
While the class keyword is the modern standard for structuring object-oriented code, it is vital to understand that JavaScript relies entirely on prototypes under the hood.
Prototypal Inheritance
Instead of classes creating instances, objects inherit directly from other objects.
Use Object.create(parentObj) to create a new, empty object that uses parentObj as its prototype fallback.
const baseUser = { type: "User", canLogin: true };
// Creates a new object linked to baseUser
const adminUser = Object.create(baseUser);
adminUser.type = "Admin"; // Overrides the inherited property
console.log(adminUser.canLogin); // true (Inherited)
console.log(adminUser.type); // "Admin" (Overridden)
The Prototype Chain
When you attempt to access a property on an object (e.g., obj.name), JavaScript performs the following lookup:
- Does
objpossessnamedirectly? - If no, does
obj’s prototype possessname? - If no, does that prototype’s prototype possess
name? - This continues until it finds the property or hits the root
null(returningundefined).
Inspecting Prototypes
You can mathematically verify inheritance and inspect chains using built-in Object methods.
// Get the direct parent of an object
const parent = Object.getPrototypeOf(childObj);