// 利用 Proxy 包裹对象,使其读取不存在的变量时,不会报错,并返回 undefined ,设置变量的时候,能够自动设置其中不存在的值。
// 可选链,lodash的get
// Proxy / Reflect
const a = {}
let windowProxy = window.Proxy
const Proxy = (obj) => {
console.log(`Proxy${obj}`)
return new windowProxy(obj, {
get: function (target, propKey, receiver) {
console.log(`getting ${propKey}!`);
// console.log(target[propKey])
console.log()
if(!target[propKey]) {
let temp = Proxy({})
}
if(!target[propKey]) return {}
// try {
// } catch {
return Reflect.get(target, propKey, receiver);
// }
},
set: function (target, propKey, value, receiver) {
console.log(`setting ${propKey}!`);
return Reflect.set(target, propKey, value, receiver);
}
});
}
const b = Proxy(a)
console.log(b.a.c)
// const c = b.a
// console.log('=====', c)
// b.a.c.s // undefined
// b.a.c.bc = 1 // 不会报错
console