代理对象 拦截器的应用 通过代理才能直接访问对象
创建一个proxy对象,里面传递两个参数,代理对象和处理函数对象
1.访问属性
能处理当访问对象不存在时
var person ={
name:"小明",
age:16
}
let proxy=new Proxy(person,{
get:function(target,prop){
if(prop in target){
return target[prop]
}else{
throw new Error("访问对象属性不存在!")
}
}
})
console.log(proxy.sex)
2.数组访问(负数下标处理)
const arr=[1,23,4,89]
const proxy2 =new Proxy(arr,{
get:function(target,index){
index=Number(index)
if(index>0){
return target[index]
}else{
return target[target.length+index]
}
}
})
console.log(proxy2[-1],"数组")
3.禁止访问私有属性 不能在外部访问
const person3={
name:'cao teacher',
_pwd:'123456'
}
const proxy3=new Proxy(person3,{
get:function(target,prop){
if(prop.indexof("_")===0){
throw new Error;
}else{
return target[prop];
}
}
})
console.log(proxy3._pwd,"访问私有属性")
4.实现真正的私有,既不能访问,也不能修改
const api={
_apikey:"123erng5",
getAll:function(){
console.log("查询全部用户")
}
}
const proxy4=new Proxy(api,{
get:function(target,prop){
if(prop.indexof('_')===0){
return undefined;
}
},
set:function(target,prop,value){
if(prop[0]!==0){
return target[prop]=value;
}else{
console.log("无法修改")
}
},
has:function(target,prop){
if(prop[0]==='_'){
return false;
}else{
return prop in target;
}
}
})