proxy用法
// 代理
{
let obj={
time:'2017-03-11',
name:'net',
_r:
}; let monitor=new Proxy(obj,{
// 拦截对象属性的读取
get(target,key){
return target[key].replace('','') //将目标对象中的2017都换成2018
},
// 拦截对象设置属性
set(target,key,value){
if(key==='name'){
return target[key]=value; //当key值为name时会被修改value值
}else {
return target[key];
}
},
// 拦截key in object操作判断是否属于object的某个属性
has(target,key){
if(key==='name'){
return target[key]
}else {
return false;
}
},
// 拦截delete
deleteProperty(target,key){
if(key.indexOf('_') > -){
delete target[key];
return true;
}else {
return target[key]
}
},
// 保护属性 拦截Object.keys,Object.getOwnPropertySymbols,Object.getOwnPropertyNames
ownKeys(target){
return Object.keys(target).filter(item=>item!='time')
}
}); console.log('get',monitor.time); monitor.time='';
monitor.name='mukewan';
console.log('set',monitor.time,monitor); //set 2018-03-11 Proxy {time: "2017-03-11", name: "mukewan", _r: 123} console.log('has','name' in monitor,'time' in monitor); //true false // delete monitor.time;
// console.log('delete',monitor); //还是存在,没被删掉 // delete monitor.time;
// console.log('delete',monitor); // delete monitor._r这一项;
// console.log('delete',monitor); //发现被删除了_r这一项 console.log('ownKeys',Object.keys(monitor)); //["name", "_r"] time被保护
}
Reflect
Reflect用法跟Proxy一样,他有的方法他都有,使用起来更简单
{
let obj={
time:'2017-03-11',
name:'net',
_r:
};
console.log('Reflect get',Reflect.get(obj,'time'));
Reflect.set(obj,'name','mukewan');
console.log(obj);
console.log('has',Reflect.has(obj,'name'));
}
应用场景 数据校验
{
function validator(target,validator){
return new Proxy(target,{
_validator:validator,
set(target,key,value,proxy){
if (target,key,value,proxy) {
let va=this._validator[key];
if(!!va(value)){
return Reflect.set(target,key,value,proxy)
}else {
throw Error(`不能设置${key}到${value}`)
}
}else {
throw Error(`${key} 不存在`)
}
}
})
} const personValidators={
name(val){
return typeof val==='string'
},
age(val){
return typeof val ==='number' &&val>
},
mobile(val) { }
} class Person {
constructor(name,age){
this.name=name;
this.age=age;
return validator(this,personValidators)
}
} const person=new Person('lilei',);
console.log(person);
person.name='Han mei mei'; console.log(person);
}