Delegated behavior
Share methods or default values across related objects without copying them into every object.
JS Puzzles · Const
JavaScript resolves a missing property by searching the object's prototype, then that prototype's prototype, until it finds a match or reaches null. This linked lookup structure is the prototype chain.
An object can delegate missing property lookups to its prototype, whose own prototype is checked next. This continues until a matching property is found or the chain reaches null; Object.getPrototypeOf and Object.setPrototypeOf inspect and change that internal link.
Object.getPrototypeOf(obj)
Object.create(proto)| Name | Type | Description |
|---|---|---|
obj | object | The object whose prototype is inspected. |
proto | object or null | The prototype object to use for the new object. |
Object.getPrototypeOf() returns an object's prototype; Object.create() returns a new object using the supplied prototype.
const parent = { shared: true };
const child = Object.create(parent);
child.own = 1;
console.log(child.own); // 1
console.log(child.shared); // true
console.log(Object.getPrototypeOf(child) === parent); // true
console.log(child.missing); // undefinedThe child keeps its own property and finds shared through its prototype; an absent property remains undefined.
Share methods or default values across related objects without copying them into every object.
Inspect how an object inherits properties during debugging or puzzle solving.
Create an object with a deliberate prototype, including a null-prototype dictionary.
Object.getPrototypeOf()Object.create()Object.prototype__proto__prototype chain