JavaScript Reference ยท Object
Object.create()
Reference for JavaScript Object.create(): make a new object with a chosen prototype, build null-prototype dictionaries and define properties with descriptors.
Object.create() makes a new, empty object and sets its prototype to the object you pass in. Property lookups that fail on the new object continue on the prototype, so the new object "inherits" from it without any constructor function or class.
Passing null creates an object with no prototype at all. Such an object has no inherited methods like toString(), which makes it a clean dictionary for arbitrary keys.
const child = Object.create(parent); const dictionary = Object.create(null);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Object.create(proto) Object.create(proto, propertiesObject)
| Name | Description |
|---|---|
proto |
The object to use as the prototype of the new object, or null for no prototype. |
propertiesObject |
Optional. An object whose own enumerable properties are property descriptors, in the same format as Object.defineProperties(). |
Return value: the new object.
Exceptions: a TypeError if proto is not an object or null (for example undefined or a number).
Usage notes
- Descriptors default to false. Properties added through the second argument are not writable, enumerable or configurable unless you say so. That is the opposite of properties created with plain assignment.
- Shallow chain, live link. The prototype is referenced, not copied. Adding a method to the prototype later makes it visible on every object created from it.
- Null-prototype objects are safe for use as maps of user-supplied keys, because keys such as
__proto__orconstructordo not collide with inherited members. They also lackhasOwnProperty, so test keys withObject.hasOwn()or theinoperator. AMapis often the better choice. - Not a copy.
Object.create(obj)does not cloneobj. The new object starts empty. To copy properties use spread orObject.assign(). - Printing a null-prototype object is fine in consoles, but string conversion such as
${obj}throws aTypeError, because there is notoString. - Classes and
newdo the same job with more structure:classsets up the prototype of instances for you.Object.create()is handy for pure prototype-based designs and for setting up inheritance by hand.
Browser support
Object.create() is available in every browser and JavaScript runtime.