属性描述符

我们知道,对象中包括各种属性,而属性描述符(Property Descriptor)就是用来描述这些属性的,它本质上还是一个普通对象,通过以下四个方面来对属性进行描述

1)value:属性值

2)configurable:该属性的描述符是否可以修改,即属性描述符这个对象里的内容能否被修改

3)enumerable:该属性是否可以被枚举

4)writable:该属性是否可以被重新赋值

我们可以通过Object.getOwnPropertyDescriptor(对象,属性名) 得到一个对象的某个属性的属性描述符,要得到某个对象的所有属性描述符可以使用Object.getOwnPropertyDescriptors(对象),举个栗子

【例1】

const obj = {
    a: 1,
    b: 2
}
const result1 = Object.getOwnPropertyDescriptor(obj, "a");
const result2 = Object.getOwnPropertyDescriptors(obj);
console.log('属性a的属性描述符:',result1);
console.log('所有属性的属性描述符:',result2);

【结果】

如果需要为某个对象添加属性或修改属性时,配置其属性描述符,可以使用Object.definProperty(对象,属性名,描述符)或者Object.defineProperties(对象,多个属性的描述符),下面分别对属性描述符的四个属性进行修改,分别康康它们的作用是什么

【例2】

1)修改value值

const obj = {
    a: 1,
    b: 2
}
Object.defineProperty(obj, "a", {
    value: 4,
    configurable: true,
    enumerable: true,
    writable: true
})
console.log(obj)

【结果】

2)修改configurable的值为false

const obj = {
    a: 1,
    b: 2
}
Object.defineProperty(obj, "a", {
    value: 4,
    configurable: false,
    enumerable: true,
    writable: true
})
//设置configurable为false后,属性描述符中的属性是不能被修改的,因此下面的代码会报错
Object.defineProperty(obj, "a", {
    value: 10,
    configurable: true,
    enumerable: false,
    writable: true
})

【结果】

 3)修改enumerable的值为false

const obj = {
    a: 1,
    b: 2
}
Object.defineProperty(obj, "a", {
    value: 4,
    configurable: true,
    enumerable: false,
    writable: true
})
console.log("obj:",obj);
for (const key in obj) {
    console.log('可被枚举的属性:',key);
}

【结果】

4)修改writable属性

const obj = {
    a: 1,
    b: 2
}
Object.defineProperty(obj, "a", {
    value: 4,
    configurable: true,
    enumerable: true,
    writable: false
})
//设置了不可写属性,所以下面这条语句不会起作用
obj.a = 10;
console.log(obj);

 【结果】

【例3】试一试 Object.defineProperties(对象,多个属性的描述符)叭~

const obj = {
    a: 1,
    b: 2
}
Object.defineProperties(obj, {
    //修改a属性的属性描述符
    a: {  
        value: 4,
        configurable: true,
        enumerable: true,
        writable: true
    },
    //修改b属性的属性描述符
    b: {
        value: 7,
        configurable: true,
        enumerable: true,
        writable: true
    }
})
const result = Object.getOwnPropertyDescriptors(obj)
console.log(result);

【结果】

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值