1.真的proxy
let target ={name:'张三'}
let handler = {
get(target,property,receiver){
console.log(1,target,2,property,3,receiver)
return Reflect.get(target,property,receiver)
},
set(target,property,value,receiver){
console.log('a',target,'b',property,'c',value,'d',receiver)
return Reflect.set(target,property,value,receiver)
}
}
let proxy = new Proxy(target,handler)
console.log(proxy.name)
proxy.name = '李四'
// console.log(proxy.name)
以上代码用浏览器控制台运行下如下
可知target,property,value,receiver的值
不知道为啥这里的target换成多层的对象就不起作用了
let target ={name:'张三',info:{age:18,sex:'男'}}
console.log(proxy.info.sex)
proxy.info.sex = '女'
2.自己写的proxy
很明显这里的reflect.get被return target[key]替代,
reflect.set被 '=' 替代
说明了reflect在proxy的作用
let handler = {
get(target, key, receiver) {
console.log(1, target, 2, key, 3, receiver)
return target[key];
},
set(target, key, value, receiver) {
console.log('a', target, 'b', key, 'c', value, 'd', receiver)
target[key] = value;
return true;
},
};
let target ={name:'张三'}
let proxy = new Proxy(target, handler);
console.log(proxy.name)
proxy.name = '李四'
console.log(proxy.name)