object 方法_Object getOwnPropertyDescriptors()方法

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 方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值