属性描述符就是一个属性除了属性名与属性值之外的其他相关信息
通过Object.getOwnPropertyDescriptor(对象, 属性名)可以得到一个对象的某个属性的属性描述符
let obj = {
a: 1
}
console.log(Object.getOwnPropertyDescriptor(obj, 'a'));
// {
// value: 1,
// writable: true,
// enumerable: true,
// configurable: true
// }
通过Object.getOwnPropertyDescriptors(对象)可以得到某个对象的所有属性描述符
let obj = {
a: 1,
b: 2
}
console.log(Object.getOwnPropertyDescriptors(obj));
// {
// a: {
// value: 1,
// writable: true,
// enumerable: true,
// configurable: true
// }
// b: {
// value: 2,
// writable: true,
// enumerable: true,
// configurable: true
// }
// }
接下来,说一说每一个属性描述符的作用
不多逼逼
当我们设置configurable为false以后,再去修改属性描述符的话,会报错
let obj = {
a: 1,
b: 2
}
Object.defineProperty(obj, 'a', {
value: 'a',
configurable: false
})
Object.defineProperty(obj, 'a', {
value: 'a',
configurable: true
})
// Uncaught TypeError: Cannot redefine property: a
// at Function.defineProperty (<anonymous>)
当设置一个属性的enumerable为false时,该属性不可被forin循环
但是不影响forof循环,因为forof循环看有没有Symbol(Symbol.iterator)
forin循环的是属性名,forof循环的是属性值