Proxy相当于Vue中的钩子函数;执行方法前,先预处理代码。
先定义一个对象的基本方法
v
1. List item
ar obj={
add:function(val){
return a+1;
},
sex:'男';
};
console.log(obj.add(100)); // 结果为101
console.log(obj.sex); // 结果为男
声明Proxy
Proxy的基本样式 new Proxy({ },{ });
第一括号代表我的主方法,第二个括号代表我们写生命周期的地方(钩子函数);
用new的方法对Proxy进行声明实例。
var star = new Proxy({
add:function(x){
return x+1;
},
name : '李四'
},{
get:function(target,key,property){
console.log('张三');
return target[key];
}
});
console.log(pro.name)
打开控制台先输出 张三
,然后输出李四
;
get属性
get属性是对象时预处理的方法,它接受3个参数
- target : 得到的目标值
- key : 目标的key值
- property : 暂时不考虑
set属性
set属性也是对象是预处理的方法,它接受4个参数
- target :得到的目标值
- key : 目标的key值
- value : 改变的值
- receiver : 改变前的原始值
var pro = new Proxy({
add: function (x) {
return x + 1;
},
name: '张三'
}, {
get:function(target,key){
console.log('李四');
return target[key];
},
set:function(target,key,value,receiver){
console.log(`${key} = ${value}`); //name=王五
return target[key] = value;
}
});
console.log(pro.name); //先输出李四 //再输出张三
pro.name='王五';
console.log(pro.name); //先输出李四 //在输出value也就是王五