object create
Introduced in ES5.
在ES5中引入。
Creates a new object, with the specified prototype.
使用指定的原型创建一个新对象。
Usage:
用法:
const newObject = Object.create(prototype)
Example:
例:
const animal = {}
const dog = Object.create(animal)
The newly create object will inherit all the prototyope object properties.
新创建的对象将继承所有原型对象的属性。
You can specify a second parameter to add new properties to the object, that the prototype lacked:
您可以指定第二个参数以向原型添加缺少的新属性:
const newObject = Object.create(prototype, newProperties)
where newProperties is an object of objects that define each property.
其中newProperties是定义每个属性的对象的对象。
Example:
例:
const animal = {}
const dog = Object.create(animal, {
breed: {
value: 'Siberian Husky'
}
});
console.log(dog.breed) //'Siberian Husky'
I didn’t just say breed: 'Siberian Husky'
but I had to pass a property descriptor object, defined at the beginning of this page.
我不只是说breed: 'Siberian Husky'
而是我必须传递在页面开头定义的属性描述符对象。
Object.create()
is often used in combination with Object.assign()
:
Object.create()
通常与Object.assign()
结合使用:
const dog = Object.assign(Object.create(animal), {
bark() {
console.log('bark')
}
})
object create