Proxy和Reflect

原因

最近在写 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也可以这样调用

原文地址:https://www.cnblogs.com/leee/p/8251512.html