function reactive(target = {}) {
if (typeof target !== 'object' || target == null) {
return target
}
const handler = {
get(target, key, receiver) {
const ownKeys = Reflect.ownKeys(target)
if (ownKeys.includes(key)) {
console.log('get', key)
}
const result = Reflect.get(target, key, receiver)
return reactive(result)
},
set(target, key, val, receiver) {
const oldVal = target[key]
if (val === oldVal) { return true }
const ownKeys = Reflect.ownKeys(target)
if (ownKeys.includes(key)) {
console.log('set 修改属性---', key, val)
} else {
console.log('set 新增属性---', key, val)
}
const result = Reflect.set(target, key, val, receiver)
console.log('result---', result)
return result
},
deleteProperty(target, key, receiver) {
const result = Reflect.deleteProperty(target, key)
console.log('deleteProperty', key)
console.log('result---', result)
return result
}
}
const observed = new Proxy(target, handler)
return observed
}
const Tom = {
name: 'Tom',
age: 18,
male: 'boy',
friend: {
name: 'Jack',
age: 10,
}
}
const proxyTom = reactive(Tom)
proxyTom.friend.name
console.log('%c------------------------', 'color:blue')
proxyTom.test = {}
console.log('%c------------------------', 'color:blue')
proxyTom.test.test = 0
console.log('%c------------------------', 'color:blue')
proxyTom.aaa.aaa = 0
console.log(Tom)