Method delegation
Share methods among related objects without copying each method onto every instance.
JS Puzzles · Const
JavaScript resolves missing properties by walking an object's prototype chain. The chain ends at null; if no object provides the property, the result is undefined.
Each object can link to another object as its prototype. When a property is missing on the object itself, JavaScript searches that prototype, then continues through successive prototypes until it finds the property or reaches null; a missing property evaluates to undefined.
Object.getPrototypeOf(obj)| Name | Type | Description |
|---|---|---|
obj | object | The object whose prototype is returned. |
The prototype object associated with the supplied object.
const parent = { greet() { return "hello"; } };
const child = Object.create(parent);
console.log(child.greet());
console.log(Object.getPrototypeOf(child) === parent);The child has no own greet method, so JavaScript finds it on parent through the prototype chain.
Share methods among related objects without copying each method onto every instance.
Inspect an object's inheritance relationship during debugging or metaprogramming.
Create an object that delegates property lookup to a selected parent object.
JavaScript first checks whether the object has the requested property. If it does not, lookup continues on the object's prototype, then on that prototype's prototype, until the property is found or the chain ends; an unsuccessful lookup produces undefined.
Follow-up: What terminates the search? The chain terminates at an object whose prototype is null.
Object.getPrototypeOf(obj) returns the object's prototype. Object.create(proto) creates a new object whose prototype is the supplied object, allowing property lookup to delegate to it.
Follow-up: How can the relationship be inspected without relying on __proto__? Use Object.getPrototypeOf, the standard access method described by the documentation.
Object.prototype is the default prototype for ordinary object literals, and its own prototype is null. Consequently, methods such as toString can be inherited through Object.prototype.
Follow-up: Why does an array also find object methods? Its prototype chain eventually reaches Object.prototype, where those methods are available.
Object.getPrototypeOf()Object.create()Object.prototype__proto__property lookupprototypal inheritance