1. 拦截对象属性的读取
{
// Proxy 代理
let obj = { //原始对象
time:'2017-03-11',
name:'net',
_r:123
};
let monitor = new Proxy(obj,{
//拦截对象属性的读取
get(target,key) {
return target[key].replace('2017','2018')
}
})
console.log(monitor.time); // 2018-03-11
console.log(obj.time);// 2017-03-11
}
2. 拦截对象设置属性
{
// Proxy 代理
let obj = { //原始对象
time:'2017-03-11',
name:'net',
_r:123
};
let monitor = new Proxy(obj,{
//拦截对象设置属性
set(target,key,value) {
if(key==='name') {
return target[key] = value
} else {
return target[key]
}
}
})
monitor.name = 'xiaowang'
console.log(monitor.name);// xiaowang
console.log(obj.name);// xiaowang
monitor._r = 5555;
console.log(monitor._r);//123,没有设置成功
}
3. 拦截key in object操作
has(target,key){
if(key==='name') {
return target[key]
}else {
return false
}
}
console.log('time' in monitor); //false
4. 拦截delete
deleteProperty(target,key){
if(key.indexOf('_')>=-1) {
delete target[key];
return true;
} else {
return target[key]
}
}
delete monitor.time
console.log(monitor.time); //2017-03-11.不满足条件 所以没有被删除
5.拦截Object.keys,Object.getOwnPropertySymbols,Object,getOwnPropertyNames
{
ownKeys(target) {
return Object.keys(target).filter(item=>item!='time')
}
console.log('ownKeys',Object.keys(monitor)); // ['name','_r'] time被保护起来了
}
网友评论