Prototype-based delegation
Build objects that delegate behavior or data lookup to a shared prototype object.
JavaScript · Function
Object.create() creates a new object with a chosen prototype. An optional descriptor map defines its own properties with precise attribute control.
Object.create() makes a new object whose internal prototype is the supplied object or null. Its optional second argument defines own properties through descriptor objects, giving precise control over attributes such as writability, enumerability, and configurability.
Object.create(proto)
Object.create(proto, propertiesObject)| Name | Type | Description |
|---|---|---|
proto | object or null | The object that becomes the prototype of the newly created object; it may also be null. |
propertiesObject | object or undefined | Optional object whose enumerable own properties provide property descriptors for the new object's own properties. |
A new object with the specified prototype and properties.
const prototype = {
greet() {
return `Hello, ${this.name}`;
},
};
const person = Object.create(prototype, {
name: {
value: "Ada",
writable: true,
enumerable: true,
configurable: true,
},
});
console.log(person.greet()); // Hello, Ada
console.log(Object.getPrototypeOf(person) === prototype); // trueThe new object inherits greet from prototype, while name is defined through a property descriptor.
Build objects that delegate behavior or data lookup to a shared prototype object.
Create dictionary-like objects without inherited Object.prototype properties.
Define several own properties with explicit writability, enumerability, or configurability settings at creation time.
It returns a new object whose prototype is proto. The optional propertiesObject argument defines own properties using property descriptors rather than assigning ordinary values.
Follow-up: What happens with Object.create(null)? It creates an object whose prototype is null, so it does not inherit methods such as those from Object.prototype.
proto must be either an object or null. Passing another value causes a TypeError.
Follow-up: How can a caller avoid that exception? Validate that the prototype is null or an object before calling Object.create().
Each enumerable own property of propertiesObject describes a property to add to the new object. Descriptor fields control attributes such as value, writable, enumerable, and configurable.
Follow-up: What is the default for omitted descriptor attributes? They are false, so the resulting property is not writable, enumerable, or configurable unless enabled explicitly.
Object.defineProperties()Object.getPrototypeOf()Object.prototype__proto__new