1 //Proxy,Reflect 2 3 { 4 let obj={ 5 time:'2018-06-25', 6 name:'net', 7 _r:123 8 }; 9 let monitor = new Proxy(obj,{ 10 //拦截对象属性的读取 11 get(target,key){ 12 return target[key].replace('2018','2019') 13 }, 14 //拦截对象设置属性 15 set(target,key,value){ 16 if(key==='name'){ 17 return target[key]=value; 18 }else{ 19 return target[key]; 20 } 21 }, 22 //拦截key in object 操作 23 has(target,key){ 24 if(key==='name'){ 25 return target[key]; 26 }else{ 27 return false; 28 } 29 }, 30 //拦截delete 31 deleteProperty(target,key){ 32 if(key.indexOf('_')>-1){ 33 delete target[key]; 34 return true; 35 }else{ 36 return target[key] 37 } 38 }, 39 //拦截Object.keys,Object.getOwnPropertySymbols,Object.getOwnPropertyNames 40 ownKeys(target){ 41 return Object.keys(target).filter(item=>item!='time') 42 } 43 }); 44 console.log('get',monitor.time); 45 monitor.name='web'; 46 console.log('set',monitor.name); 47 console.log('has','name' in monitor); 48 // delete monitor.time; 49 // console.log('delete',monitor); 50 // delete monitor._r; 51 // console.log('delete',monitor); 52 console.log('ownKeys',Object.keys(monitor)); 53 } 54 { 55 56 let obj={ 57 time:'2018-06-25', 58 name:'net', 59 _r:123 60 }; 61 console.log('Reflect get',Reflect.get(obj,'time')) 62 console.log('Reflect set',Reflect.set(obj,'time','2019-06-05')) 63 console.log(obj); 64 console.log('has',Reflect.has(obj,'name')) 65 } 66 //例子 67 68 { 69 function validator(target,validator){ 70 71 return new Proxy(target,{ 72 _validator:validator, 73 set(target,key,value,proxy){ 74 if(target.hasOwnProperty(key)){ 75 let va=this._validator[key]; 76 if(!!va(value)){ 77 return Reflect.set(target,key,value,proxy) 78 }else{ 79 throw Error(`不能设置${key}到${value}`) 80 } 81 }else{ 82 throw Error(`${key} 不存在`) 83 } 84 } 85 }) 86 } 87 const personValidators={ 88 name(val){ 89 return typeof val==='string' 90 }, 91 age(val){ 92 return typeof val==='number'&&val>18 93 } 94 } 95 class Person{ 96 constructor(name,age){ 97 this.age=age; 98 this.name=name; 99 return validator(this,personValidators) 100 } 101 } 102 const person = new Person('lilei',30); 103 console.info(person) 104 person.name="qqq qq"; 105 console.info(person) 106 }