從 Vue3 源碼學(xué)習(xí) Proxy & Reflect
這兩個(gè)功能都出現(xiàn)在ES6中,兩者配合得非常好!
Proxy
**proxy **是一個(gè)外來(lái)的對(duì)象,他沒(méi)有屬性! 它封裝了一個(gè)對(duì)象的行為。它需要兩個(gè)參數(shù)。
- const toto = new Proxy(target, handler)
**target: **是指將被代理/包裹的對(duì)象 **handler: **是代理的配置,它將攔截對(duì)目標(biāo)的操作(獲取、設(shè)置等)
多虧了 proxy ,我們可以創(chuàng)建這樣的 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 !
每個(gè)內(nèi)部對(duì)象的 "方法" 都有他自己的目標(biāo)函數(shù)
下面是一個(gè)對(duì)象方法的列表,相當(dāng)于進(jìn)入了 Target:
- object methodtargetobject[prop]getobject[prop] = 55setnew Object()constructObject.keysownKeys
目標(biāo)函數(shù)的參數(shù)可以根據(jù)不同的函數(shù)而改變。
例如,對(duì)于get函數(shù)取(target, prop, receiver(proxy本身)),而對(duì)于 set 函數(shù)取(target, prop, value (to set), receiver)
例子
我們可以創(chuàng)建私有屬性。
- 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方法返回布爾值
- // 以便讓我們知道該值是否已被正確設(shè)置 !
- 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 是一個(gè)靜態(tài)類,簡(jiǎn)化了 proxy 的創(chuàng)建。
每個(gè)內(nèi)部對(duì)象方法都有他自己的 Reflect 方法
- object methodReflectobject[prop]Reflect.getobject[prop] = 55Reflect.setobject[prop]Reflect.getObject.keysReflect.ownKeys
❓ 為什么要使用它?因?yàn)樗蚉roxy一起工作非常好! 它接受與 proxy 的相同的參數(shù)!
- const toto = { a: 55, b:66 }
- const handler = {
- get(target, prop, receiver) {
- // 等價(jià) 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) {
- // 等價(jià) target[prop] = value
- // Reflect.set 返回 boolean
- return Reflect.set(target, prop, receiver)
- },
- }
- const totoProxy = new Proxy (toto, handler)
所以你可以看到 Proxy 和 Reflect api是很有用的,但我們不會(huì)每天都使用它,為了制作陷阱或隱藏某些對(duì)象的屬性,使用它可能會(huì)很好。
如果你使用的是Vue框架,嘗試修改組件的 props 對(duì)象,它將觸發(fā)Vue的警告日志,這個(gè)功能是使用 Proxy :) !
作者:CodeOz 譯者:前端小智
來(lái)源:dev 原文:https://dev.to/codeoz/proxy-reflect-api-in-javascript-51la