//Proxy基本使用
{
let obj = {
time:'2017-03-11',
name:'net',
_r:123
};
let monintor=new Proxy(obj,{
// 拦截对象属性的读取改变
get(target,key){
return target[key].replace('2017','2018')
},
// 拦截对象设置属性
set(target,key,value){
if(key == 'name'){
return target[key] = value;
}else{
return target[key];
}
},
// 拦截key in object 操作
has( target , key ){
if( key === 'name' ){
return target[key];
}else{
return false;
}
},
// 拦截delete
deleteProperty(target,key){
if( key.indexOf('_') > -1 ){
delete target[key];
return true;
}else{
return target[key];
}
},
// 拦截object.keys,object.getOwnPropertySymbols等方法
ownKeys(target){
return Object.keys(target).filter(item=>item != 'time');
}
});
// get
console.log( 'get',monintor.time);
//set
monintor.time = '2019';
console.log( 'set',monintor.time);
monintor.name = 'shuaizi';
console.log( 'set',monintor.name);
// has
console.log('has','name' in monintor,'time' in monintor);
// delete
delete monintor.name;
console.log('delete',monintor);
delete monintor._r;
console.log('delete',monintor);
// ownKeys
console.log('ownKeys',Object.keys(monintor));
}
//Reflect 基本使用
{
let obj = {
time:'2017-03-11',
name:'net',
_r:123
};
// 调取对象
console.log(Reflect.get(obj,'time'));
// 改变属性
Reflect.set(obj,'name','shuaizi');
console.log(obj);
// 查看是否存在这个属性
console.log(Reflect.has(obj,'time'));
// 删除属性
Reflect.deleteProperty(obj,'_r');
console.log(obj);
}
案例
{
function validator(target,validator){
return new Proxy(target,{
_validator:validator,
set(target,key,value,proxy){
if(target.hasOwnProperty(key)){
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>18
},
// 可以增加验证条件
}
class Person{
constructor(name,age){
this.name=name;
this.age=age;
// 可以增加验证
return validator(this,personValidators)
}
}
// 调用方法
const person=new Person('lilei',30);
console.info(person);
// 修改属性
person.name='Han mei mei';
console.log(person);
}