let subscribe = (obj,observable) => {
let handler = {
get(target, property, receiver) {
console.log(`'${property}' 的值为 ${target[property]}`)
observable(arguments)
return Reflect.get(target, property, receiver)
},
set(target, property, value, receiver) {
console.log(`监听到属性${property}改变为${value}`)
observable(arguments)
return Reflect.set(target, property, value)
}
}
return new Proxy(obj, handler)
}
let obj = { a: 1 }
let p = subscribe(obj,(args)=>{
console.log(args)
})
p.a = 2 // 监听到属性a改变
p.a // 'a' = 2
console