const target = Object.create({ name: 'richard', info: { message: 'hello', haha: '' } })
function createProxy(target) {
const proxyMap = new WeakMap()
const reactive = target => {
const existProxy = proxyMap.get(target)
// 如果目标对象已经被代理过,则直接返回即可
if (existProxy) {
return existProxy
}
const proxy = {}
for (const key in target) {
proxyKey(proxy, target, key)
}
// 将代理对象缓存起来
proxyMap.set(target, proxy);
return proxy
}
const proxyKey = (proxy, target, key) => {
Object.defineProperty(proxy, key, {
enumerable: true,
configurable: true,
get() {
const res = target[key];
console.log(`获取 ${key}: ${JSON.stringify(res)}`)
if (typeof res === 'object') {
return reactive(res);
}
return res;
},
set (value) {
console.log(`设置 ${key}: ${value}`)
target[key] = value;
}
})
}
return reactive(target)
}
const proxy = createProxy(target);
proxy.name = 'sherman';
console.log(target.name)
console.log(proxy.info.message)
console.log('---------------------------------')
function createProxy2(getTarget) {
const proxyMap = new WeakMap()
const reactive = getTarget => {
const target = getTarget()
const existProxy = proxyMap.get(target)
// 如果目标对象已经被代理过,则直接返回即可
if (existProxy) {
return existProxy
}
const proxy = {}
for (const key in target) {
proxyKey(proxy, getTarget, key)
}
// 将代理对象缓存起来
proxyMap.set(target, proxy);
return proxy
}
const proxyKey = (proxy, getTarget, key) => {
Object.defineProperty(proxy, key, {
enumerable: true,
configurable: true,
get() {
const target = getTarget()
const res = target[key];
console.log(`获取 ${key}: ${JSON.stringify(res)}`)
if (typeof res === 'object') {
return reactive(() => res);
}
return res;
},
set (value) {
const target = getTarget()
console.log(`设置 ${key}: ${value}`)
target[key] = value;
}
})
}
return reactive(getTarget)
}
const proxy1 = createProxy2(() => target.info)
console.log(proxy1.message) // hello
target.info = { message: 'hehe', haha: { text: 'hahaha' } }
setTimeout(() => {
console.log(proxy1.message) // hehe
console.log(proxy1.haha.text) // hahaha
}, 100)
console