Proxy代理和拦截器

代理对象 拦截器的应用 通过代理才能直接访问对象
创建一个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;
            }
        }
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值