作者:CodeOz
译者:前端小智
起源:dev
有幻想,有干货,微信搜寻 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。
本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。
这两个性能都呈现在ES6中,两者配合得十分好!
Proxy
proxy 是一个外来的对象,他没有属性! 它封装了一个对象的行为。它须要两个参数。
const toto = new Proxy(target, handler)
target: 是指将被代理/包裹的对象
handler: 是代理的配置,它将拦挡对指标的操作(获取、设置等)
多亏了 proxy ,咱们能够创立这样的 traps
:
const toto = { a: 55, b:66 }
const handler = {
get(target, prop, receiver) {
if (!!target[prop]) {
return target[prop]
}
return `This ${prop} prop don't exist on this object !`
}
}
const totoProxy = new Proxy (toto, handler)
totoProxy.a // 55
totoProxy.c // This c prop don't exist on this object !
每个外部对象的 “办法” 都有他本人的指标函数
上面是一个对象办法的列表,相当于进入了 Target:
object method | target |
---|---|
object[prop] | get |
object[prop] = 55 | set |
new Object() | construct |
Object.keys | ownKeys |
指标函数的参数能够依据不同的函数而扭转。
例如,对于get
函数取(target, prop, receiver(proxy自身)),而对于 set
函数取(target, prop, value (to set), receiver)
例子
咱们能够创立公有属性。
const toto = {
name: 'toto',
age: 25,
_secret: '***'
}
const handler = {
get(target, prop) {
if (prop.startsWith('_')) {
throw new Error('Access denied')
}
return target[prop]
},
set(target, prop, value) {
if (prop.startsWith('_')) {
throw new Error('Access denied')
}
target[prop] = value
// set办法返回布尔值
// 以便让咱们晓得该值是否已被正确设置 !
return true
},
ownKeys(target, prop) {
return Object.keys(target).filter(key => !key.startsWith('_'))
},
}
const totoProxy = new Proxy (toto, handler)
for (const key of Object.keys(proxy1)) {
console.log(key) // 'name', 'age'
}
Reflect
Reflect 是一个动态类,简化了 proxy 的创立。
每个外部对象办法都有他本人的 Reflect 办法
object method | Reflect |
---|---|
object[prop] | Reflect.get |
object[prop] = 55 | Reflect.set |
object[prop] | Reflect.get |
Object.keys | Reflect.ownKeys |
❓ 为什么要应用它?因为它和Proxy一起工作十分好! 它承受与 proxy 的雷同的参数!
const toto = { a: 55, b:66 }
const handler = {
get(target, prop, receiver) {
// 等价 target[prop]
const value = Reflect.get(target, prop, receiver)
if (!!value) {
return value
}
return `This ${prop} prop don't exist on this object !`
},
set(target, prop, value, receiver) {
// 等价 target[prop] = value
// Reflect.set 返回 boolean
return Reflect.set(target, prop, receiver)
},
}
const totoProxy = new Proxy (toto, handler)
所以你能够看到 Proxy 和 Reflect api是很有用的,但咱们不会每天都应用它,为了制作陷阱或暗藏某些对象的属性,应用它可能会很好。
如果你应用的是Vue框架,尝试批改组件的 props
对象,它将触发Vue的正告日志,这个性能是应用 Proxy
🙂 !
代码部署后可能存在的BUG没法实时晓得,预先为了解决这些BUG,花了大量的工夫进行log 调试,这边顺便给大家举荐一个好用的BUG监控工具 Fundebug。
原文:https://dev.to/codeoz/proxy-r…
交换
有幻想,有干货,微信搜寻 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。
本文 GitHub https://github.com/qq44924588… 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。
发表回复