JavaScript Object的defineProperty / getOwnPropertyDescriptor
getOwnPropertyDescriptor and defineProperty
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
})
}
const obj = {}
def(obj,'name','leslie',true)
def(obj,'age',18,false)
def(obj,'company','ibm',true)
// 🚀 测试 enumerable
for(let [key,value] of Object.entries(obj)){
// 🚀🚀 只会打印出 name 和 company属性
// 🚀🚀 因为 age 是不可枚举的属性
console.info(`${key}:${value}`)
}
// 测试 🚀getOwnPropertyDescriptor
const property = Object.getOwnPropertyDescriptor(obj,'age')
/*
{
configurable: true,
enumerable: false,
value: 18,
writable: true,
}
*/
console.info(property)
// 🚀🚀 对象属性获取,兼容模式
const name = obj && obj.name
const test = obj && obj.test || 'test'
console.info(name) // 🚀 leslie
console.info(test) // 🚀 test
Keep learning