Why can one JavaScript object use a property it never defined? If the property is missing, JavaScript looks on that object’s prototype. The search can continue through a prototype chain until it finds the property or runs out of objects. Both data properties and methods can be inherited this way. section 9.3.1
Follow a property lookup
const base = { move: true }; const middle = { hide: true }; const agent = { name: "A" }; Object.setPrototypeOf(agent, middle); Object.setPrototypeOf(middle, base); console.assert("move" in agent); // Found through middle, then base console.assert(!Object.hasOwn(agent, "move")); // Not agent’s own property Changing middle’s prototype gives agent access to move without adding a property to agent. section 9.3.1
This differs from the class-based inheritance familiar from languages such as Java or C#: the fallback is a relationship between objects. Object.setPrototypeOf can change that relationship at runtime. To distinguish access through a prototype from ownership, compare the in operator with Object.hasOwn. section 1.1 section 9.3.1
Listing 9.4 With prototypes, objects can fall back on other objects
const yoshi = { skulk: true }; #A
const hattori = { sneak: true }; #A
const kuma = { creep: true }; #A
console.assert("skulk" in yoshi, "Yoshi can skulk");
console.assert(!("sneak" in yoshi), "Yoshi cannot sneak");
console.assert(!("creep" in yoshi), "Yoshi cannot creep");
Object.setPrototypeOf(yoshi, hattori); #B
console.assert("sneak" in yoshi, "Yoshi can now sneak"); #C
console.assert(
!("creep" in hattori),
"Hattori cannot creep",
);
Object.setPrototypeOf(hattori, kuma);
console.assert("creep" in hattori, "Hattori can now creep"); #D
console.assert("creep" in yoshi, "Yoshi can also creep"); #D
The listing links three objects one at a time, making each newly inherited property visible through the in operator. section 9.3.1
Constructors provide another route to the same mechanism: new X() creates an object whose prototype is X.prototype. An ordinary object literal also has a prototype, Object.prototype. A function’s prototype property is therefore not the prototype of the function itself; it is the object used by instances created with new. section 9.3.2
See what class syntax creates
class Agent { move() { return true; } } const agent = new Agent(); console.assert(typeof Agent.prototype.move === "function"); console.assert(agent.move()); console.assert(agent instanceof Agent); The method is on the class’s prototype, not assigned separately to each instance. instanceof checks whether that prototype appears in the object’s prototype chain. section 9.4.1
Classes, introduced in ES2015, offer a simpler way to define constructors and inherited methods; they do not replace prototype lookup underneath. Direct prototype manipulation remains useful for understanding object behavior, though TypeScript makes the older constructor-and-prototype pattern less straightforward to type than a class. section 9.0 section 9.3.2




