javascript中的描述对象(Descriptor)

对象的每个属性都有一个描述对象(Descriptor),用来控制该属性的行为。Object.getOwnPropertyDescriptor方法可以获取该属性的描述对象。

获取对象中属性描述对象

Object.getOwnPropertyDescriptor(obj, propName)
参数:第一个参数是目标对象,第二个参数是目标对象的目标属性。
返回值:该属性描述对象

如:

const obj = {
    item: 'hello',
    msg:'hi'
}
Object.getOwnPropertyDescriptor(obj, 'item')
{
    value: 'hello',
    writable: true,
    enumerable: true,
    configurable: true
}

如:value表示值,enumerable表示是否可枚举

比如对象的通用方法toString(),数组的length属性,其描述对象的enumerable属性的都是false。
这就解决了我一个之前的一个疑问。遍历对象中的属性怎么不会循环出对象内置的属性方法。

获取对象中全部属性的属性描述对象

Object.getOwnPropertyDescriptors(obj)
参数:想要获取的对象
返回值: 描述对象集合

属性描述对象的定义

Object.defineProperty(obj, propName, descriptorObj)
参数:第一个参数目标对象,第二个参数是属性名,第三个参数是属性描述对象。
返回值: 修改后的对象

如:

const obj = Object.defineProperty({}, 'item', {
  item: 'hello',
  writable: true,
  enumerable: true,
  configurable: true
});

// 当然,这样定义只是为了定义描述对象。
// 直接
obj.item = hello   // 最终也和上面一样

obj.item // "hello"

原文链接:https://www.cnblogs.com/lsAxy/p/12818972.html

posted @ 2020-10-16 11:22  余以为  阅读(401)  评论(0编辑  收藏  举报