object 方法
This method returns all own (non-inherited) properties descriptors of an object.
此方法返回对象的所有自己的(非继承)属性描述符。
Object.getOwnPropertyDescriptors(obj)
accepts an object, and returns a new object that provides a list of the descriptors.
Object.getOwnPropertyDescriptors(obj)
接受一个对象,并返回一个提供描述符列表的新对象。
Example:
例:
const dog = {}
Object.defineProperties(dog, {
breed: {
value: 'Siberian Husky'
}
})
Object.getOwnPropertyDescriptors(dog)
/*
{
breed: {
value: 'Siberian Husky',
writable: false,
enumerable: false,
configurable: false
}
}
*/
There is one use case that makes this property very useful. ES2015 gave us Object.assign()
, which copies all enumerable own properties from one or more objects, and return a new object. However there is a problem with that, because it does not correctly copies properties with non-default attributes.
有一个用例使此属性非常有用。 ES2015给了我们Object.assign()
,它从一个或多个对象复制了所有可枚举的自身属性,并返回一个新对象。 但是,这有一个问题,因为它不能正确复制具有非默认属性的属性。
If an object for example has just a setter, it’s not correctly copied to a new object, using Object.assign()
. For example with this object:
例如,如果某个对象只有一个setter,则无法使用Object.assign()
将其正确复制到新对象。 例如与此对象:
const person1 = {
set name(newName) {
console.log(newName)
}
}
This copy attempt won’t work:
此复制尝试将无效:
const person2 = {}
Object.assign(person2, person1)
But this will work and copy over the setter correctly:
但这可以正常工作并正确复制到设置器上:
const person3 = {}
Object.defineProperties(person3,
Object.getOwnPropertyDescriptors(person1))
As you can see with a console test:
您可以通过控制台测试看到:
person1.name = 'x'
"x"
person2.name = 'x'
person3.name = 'x'
"x"
person2
misses the setter, it was not copied over.
person2
错过了设置者,它没有被复制。
The same limitation goes for shallow cloning objects with Object.create()
.
同样的限制也适用于使用Object.create()
进行浅层克隆的对象。
翻译自: https://flaviocopes.com/javascript-object-getownpropertydescriptors/
object 方法