欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈es6语法 (Proxy和Reflect的对比)

程序员文章站 2022-04-28 23:23:55
如下所示: { //原始对象 let obj={ time:'2017-03-11', name:'net', _r:123 };...

如下所示:

{ 

 //原始对象
 let obj={
 time:'2017-03-11',
 name:'net',
 _r:123
 };
 //(代理商)第一个参数代理对象,第二个参数真正代理的东西
 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;
  }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,object.getownpropertynames
 ownkeys(target){
  return object.keys(target).filter(item=>item!='time')
 }
 });

 console.log('get',monitor.time); //2018-03-11
 //操作
 monitor.time='2018';
 monitor.name='mukewang';
 console.log('set',monitor.time,monitor);//2018-03-11;{time: "2017-03-11", name: "mukewang", _r: 123}

 console.log('has','name' in monitor,'time' in monitor);//true;false

 delete monitor.time;
 console.log('delete',monitor);//{time: "2017-03-11", name: "mukewang", _r: 123}
 //
 delete monitor._r;
 console.log('delete',monitor);//{time: "2017-03-11", name: "mukewang"}

 console.log('ownkeys',object.keys(monitor));//["name", "_r"]

}

{
 let obj={
 time:'2017-03-11',
 name:'net',
 _r:123
 };

 console.log('reflect get',reflect.get(obj,'time'));//get 2017-03-11
 reflect.set(obj,'name','mukewang');
 console.log(obj);//{time: "2017-03-11", name: "mukewang", _r: 123}
 console.log('has',reflect.has(obj,'name'));//true
}

以上这篇浅谈es6语法 (proxy和reflect的对比)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。