属性描述符与Proxy的区别&Vue3.0为何改用Proxy

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
//     }
// }


接下来,说一说每一个属性描述符的作用

value-属性值

不多逼逼

configurable-属性描述符是否可被修改

当我们设置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-该属性是否可被枚举

当设置一个属性的enumerable为false时,该属性不可被forin循环
但是不影响forof循环,因为forof循环看有没有Symbol(Symbol.iterator)
forin循环的是属性名,forof循环的是属性值


分享本文至:

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档