当前位置: 首页 > Web前端 > HTML

代理学习

时间:2023-03-29 13:14:54 HTML

1。接收者和代理中的这个?让obj=newProxy({},{get:function(target,propKey,receiver){returnReflect.get(target,propKey,receiver);},set:function(target,propKey,value,receiver){returnReflect.set(target,propKey,value,receiver);}});可以看到get和set拦截中的参数receiver,具体是什么?我们可以理解为最初调用的对象,例如:get(target,key,receiver){console.log(receiver)returntarget[key]}})letpig={_name:'pig',__proto__:animalProxy}//console.log(receiver)是对象animalProxy//console.log(this._name)foranimalanimalProxy.getName()//console.log(receiver)forobjectpig//console.log(this._name)forpigpig.getName()在这个例子中我们打印After查看this._name和receiver,可以发现其实和this在function上的机制是一致的,谁调用谁就指向谁。Tips:代理运行时不要在代理中打印receiver。访问receiver时,会经过get拦截器,导致死循环。所谓“internalslots”,类似于对象的私有属性,不允许外部访问,所以当代理不处理它们时,直接代理就会出错。letmap=newMap()letmapProxy=newProxy(map,{get(target,prop){returntarget[prop]},set(target,prop,val){target[prop]=val返回true}})//UncaughtTypeError:MethodMap.prototype.setcalledonincompatiblereceiver#atProxy.setmapProxy.set('name','ZhangSan')如果调用这个,this指向代理对象,有no这个内部槽属性,所以报错。一种处理方法是在识别内部槽属性时改变this点:'?value.bind(target):value}})//成功mapProxy.set('name','张三')3.Proxy.revocable在遇到一些业务时撤销代理,可以使用Proxy.revocable来实现与具体业务解耦,例如:Button1Button2changeextra//现在有几个按钮,点击后会执行一些操作,//还有一个配置开关,点击这些按钮会触发一些额外的动作letaction={btnClick1:function(){console.log('点击按钮1')},btnClick2:function(){console.log('clickbutton2')}}letextraAction={btnClick1:function(){console.log('button1extraaction')},btnClick2:function(){console.log('Button2extraaction')}}constactions=newWeakMap()constrevokes=newWeakMap()constproxyAction=(action)=>{const{proxy,revoke}=Proxy.revocable(action,{get(target,key){//如果有额外的动作则执行if(extraAction[key]){extraAction[key]()}returnReflect.get(...arguments)}})revokes.set(proxy,revoke)actions.set(proxy,action)returnproxy}constrevokeAction=(action)=>{constrevoke=revokes.get(action)if(revoke){revoke()//返回revoke后的原始对象returnactions.get(动作)}else{返回动作}}让isExtra=falseconstchangeExtra=()=>{isExtra=!isExtraaction=isExtra?proxyAction(action):revokeAction(action)}结束我前端新人周晓阳写文章记录自己在日常工作中遇到的问题和学习到的内容,以此来提升自己。如果您觉得本文对您有用,请点赞鼓励一下吧~