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

网友投稿 260 2023-03-23


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

如下所示:

{

//原始对象

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.getOwnPropertyNameshttp://

ownKeys(target){

return Object.keys(target).filter(item=>item!='time')

}

});

console.log(http://'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));//["namhttp://e", "_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

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring中的FactoryBean代码示例
下一篇:接口测试用例提取(接口测试用例提取方法)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~