The Object create() method
By Flavio Copes
Learn how JavaScript Object.create() makes an object with a prototype you choose, including null prototypes and properties defined with descriptors.
Object.create() creates a new object with the prototype you provide.
const animal = {
speak() {
return 'Hello'
}
}
const dog = Object.create(animal)
dog.speak() //'Hello'
Object.getPrototypeOf(dog) === animal //true
The properties are not copied from animal. JavaScript finds speak() by following the new object’s prototype chain.
The prototype must be an object or null. Any other value throws a TypeError.
See the MDN Object.create() reference and the ECMAScript specification for the complete behavior.
Add own properties
The optional second argument defines own properties on the new object:
const dog = Object.create(animal, {
breed: {
value: 'Siberian Husky',
writable: true,
enumerable: true,
configurable: true
}
})
dog.breed //'Siberian Husky'
Each entry must be a property descriptor, like the descriptors passed to Object.defineProperties().
Be careful with the defaults. If you only provide value, the property is not writable, enumerable, or configurable:
const dog = Object.create(animal, {
breed: {
value: 'Siberian Husky'
}
})
Object.keys(dog) //[]
Create an object without a prototype
Pass null to create an object that does not inherit from Object.prototype:
const dictionary = Object.create(null)
dictionary.javascript = 'A programming language'
Object.getPrototypeOf(dictionary) //null
This is useful for a simple string-keyed dictionary. It also means methods such as toString() and hasOwnProperty() are not inherited.
Use Object.hasOwn(dictionary, 'javascript') to check an own property.
You can combine a chosen prototype with regular enumerable properties using Object.assign():
const dog = Object.assign(Object.create(animal), {
breed: 'Siberian Husky'
})Related posts about js: