function observe(target) {
if (typeof target !== 'object' || target == null) {
return target
}
const observed = new Proxy(target, {
get(target, key, receiver) {
console.log('获取:' + key)
return observe(Reflect.get(target, key, receiver))
},
set(target, key, value, receiver) {
if (value === target[key]) {
return true
}
const ownKeys = Reflect.ownKeys(target)
if (ownKeys.includes(key)) {
console.log('旧属性')
} else {
console.log('新添加属性')
}
return Reflect.set(target, key, value, receiver)
},
deleteProperty(target, key) {
console.log('删除' + key)
return Reflect.deleteProperty(target, key)
}
})
return observed
}
const data = {
name: '张三',
age: 12,
info: {
city: 'beijing'
},
list: [1, 2, 3, 4]
}
const proxyData = observe(data)
console.log(proxyData.name)
// proxyData.age = 11
// proxyData.aaa = 123123
// proxyData.list.push(222)
// console.log(proxyData.list)
// delete proxyData.aaa
console