Object. create()
Creates a new object with the given prototype.
- Returns
- A new object.
- Changes the original
- No
Example
#const hero = {
greet() {
return `Hi, I'm ${this.name}`
}
}
const noah = Object.create(hero)
noah.name = 'Noah'
console.log(noah.greet())
console.log(Object.keys(noah))
console.log(Object.getPrototypeOf(noah) === hero)Definition and usage
#The Object.create(proto) method creates an empty object whose prototype is the given object. The new object inherits all its properties and methods, even though it doesn’t contain them itself.
It’s the basic inheritance mechanism in JavaScript, the one classes are built on too. In everyday code, the class syntax is used more often, but Object.create() helps you understand how the prototype chain works.
Calling Object.create(null) creates an object with no prototype at all. Such a "clean dictionary" has no inherited keys like toString, which can be handy when storing arbitrary data.
Syntax
#Object.create(proto)
Object.create(proto, propertiesObject)Parameters
#proto
object or null
The prototype of the new object.propertiesObject
optional
Property descriptors to define right away.
More examples
#const dictionary = Object.create(null)
dictionary.toString = 'just a key'
console.log(dictionary.toString)
console.log('hasOwnProperty' in dictionary)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In new code, the
classsyntax is usually more convenient for inheritance. - For dictionaries with arbitrary keys,
Mapis often a better fit.
Related entries
#- classDefines a class: a template for creating objects that share the same fields and methods.
- thisA keyword pointing to the object a function was called on.
- Object.hasOwn()Checks whether an object has its own property with the given name.
- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
Spotted a mistake or missing an example? Write to us.