Vue3 源码学习 Proxy 和 Reflect功能

目录
文章目录隐藏
  1. Proxy
  2. Reflect

这两个功能都出现在 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

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Vue3 源码学习 Proxy 和 Reflect功能

发表回复