JavaScript中对象属性的描述,可枚举,可配置,可重写...你了解过吗?
首先建立一个对象
const student = {
name: "小明",
age: 12,
[Symbol("level")]: "优秀",
[Symbol("level")]: "有钱"
}
通过Object.getOwnPropertyDescriptor获取属性值并输出
const val = Object.getOwnPropertyDescriptor(student,"name")
console.log(val) // {value: "小明", writable: true, enumerable: true, configurable: true}
/*
{
configurable: true //属性是否可以删除
enumerable: true //属性是否可以枚举
value: "小明" //属性值
writable: true //属性是否可以修改
}
*/
再通过Object.defineProperty添加属性,可以按照上面的规则修改
例
Object.defineProperty(student,"gender",{
configurable: true,
enumerable: true,
value: "男",
writable: true
})
console.log(student) //{name: "小明", age: 12, gender: "男", Symbol(level): "优秀", Symbol(level): "有钱"}