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

从Vue3源码学习Proxy&Reflect

时间:2023-03-27 16:05:36 JavaScript

微信搜索【大举走向世界】,第一时间与大家分享前端行业动态、学习方法等。本文已收录到GitHubhttps://github.com/qq449245884/xiaozhi,里面有完整的测试站点、资料和我的一线厂商访谈系列文章。Proxyproxy是外来物,他没有属性!它封装了对象的行为。它需要两个参数。consttoto=newProxy(target,handler)target:指的是将被代理/包装的对象handler:是代理的配置,会拦截对目标的操作(get,set等)感谢代理我们可以创建类似这样的陷阱:consttoto={a:55,b:66}consthandler={get(target,prop,receiver){if(!!target[prop]){returntarget[prop]}return`此对象上不存在此${prop}属性!`}}consttotoProxy=newProxy(toto,handler)totoProxy.a//55totoProxy.c//此对象上不存在此c属性!“每个内部对象的方法”都有自己的targetfunction下面是对象方法列表,相当于进入Target:objectmethodtargetobject[prop]getobject[prop]=55setnewObject()constructObject.keysownKeys的参数目标功能可以根据不同的功能而改变。例如,get函数取(target,prop,receiver(代理本身))和set函数取(target,prop,value(toset),receiver)。我们可以创建私有属性。consttoto={name:'toto',age:25,_secret:'***'}consthandler={get(target,prop){if(prop.startsWith('_')){thrownewError('拒绝访问')}returntarget[prop]},set(target,prop,value){if(prop.startsWith('_')){thrownewError('Accessdenied')}target[prop]=value///set方法返回一个布尔值//让我们知道值是否设置正确!返回true},ownKeys(target,prop){returnObject.keys(target).filter(key=>!key.startsWith('_'))},}consttotoProxy=newProxy(toto,handler)for(constkeyofObject.keys(proxy1)){console.log(key)//'name','age'}ReflectReflect是一个静态类,它简化了代理的创建。每个内部对象方法都有自己的Reflect方法objectmethodReflectobject[prop]Reflect.getobject[prop]=55Reflect.setobject[prop]Reflect.getObject.keysReflect.ownKeys?为什么要用呢?因为它与Proxy配合得很好!它接受与代理相同的参数!consttoto={a:55,b:66}consthandler={get(target,prop,receiver){//相当于target[prop]constvalue=Reflect.get(target,prop,receiver)if(!!value){returnvalue}return`This${prop}propdonotexistonthisobject!`},set(target,prop,value,receiver){//等效的target[prop]=value//Reflect.setreturnsbooleanreturnReflect.set(target,prop,receiver)},}consttotoProxy=newProxy(toto,handler)所以你可以看到Proxy和Reflectapi很有用,但我们不是每天都用它来制作陷阱或隐藏某些对象的属性,使用它可能会很好。如果你使用的是Vue框架,尝试修改组件的props对象,会触发Vue警告日志,这个功能就是要用到Proxy:)!代码部署后可能存在的bug,无法实时获知。事后为了解决这些bug,花费了大量的时间在日志调试上。顺便推荐一个好用的BUG监控工具,Fundebug。原文:https://dev.to/codeoz/proxy-r...交流有梦想,有干货,微信搜索【大招走向世界】关注这位早期还在洗碗的洗碗智慧早晨。本文GitHubhttps://github.com/qq44924588...已收录,有完整的测试站点、资料和我的一线厂商访谈系列文章。