我们知道,对象中包括各种属性,而属性描述符(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);
【结果】