Proxy和Reflect

自古美人都是妖i 提交于 2019-11-27 09:20:20

原因

最近在写 unar.js(一个技术超越react angular vue)的mvvm库。通过研究proxy的可行性。故作以下研究

Proxy代理一个函数

var fn=function(){
    console.log("fn")
}
var proxyFn=new Proxy(fn,{
    apply:function(target,scope,args){      
        target()
    }
})
proxyFn()//fn
proxyFn.call(window)//fn
proxyFn.apply(window)//fn

//通过proxy的平常调用,call,apply调用都走代理的apply方法
//这个方法参数可以穿目标代理函数,目标代理函数的作用域,和参数

Proxy引入Reflect本质

var fn=function(...args){
    console.log(this,args)
}
var proxyFn=new Proxy(fn,{
    apply:function(target,scope,args){      
        target.call(scope,...args)
    }
})
proxyFn(1)//Window,[1]
proxyFn.call(window,1)//Window,[1]
proxyFn.apply(window,[1])//Window,[1]

Reflect实用

//Relect.apply有对函数调用的时候的封装。
//Relect.apply(fn,scope,args)

var fn=function(...args){
    console.log(this,args)
}
var proxyFn=new Proxy(fn,{
    apply:function(target,scope,args){      
        Reflect.apply(...arguments)
    }
})
proxyFn(1)//Window,[1]
proxyFn.call(window,1)//Window,[1]
proxyFn.apply(window,[1])//Window,[1]

Proxy、Reflect实用

一般我们会将代理的变量名proxyFn命名成代理的对象的名字fn。

var fn=function(...args){
    console.log(this,args)
}
var fn=new Proxy(fn,{
    apply:function(target,scope,args){      
        Reflect.apply(...arguments)
    }
})
fn(1)//Window,[1]
fn.call(window,1)//Window,[1]
fn.apply(window,[1])//Window,[1]

Reflect.apply(fn,window,[1])明白了Reflect也可以这样调用

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!