2020-4-21 前端達人
屬性描述符就是一個屬性除了屬性名與屬性值之外的其他相關信息
通過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循環的是屬性值