zoukankan      html  css  js  c++  java
  • 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也可以这样调用

  • 相关阅读:
    CSS中的外边距合并问题
    Web性能优化的途径
    HTML5读书笔记——canvas元素(续)
    HTML5读书笔记——canvas元素
    2016/9/8日志
    【每日一醒】【架构师之路】设计文档之惑
    华为是个好公司,但不全是好员工——记初次压力面试的体验
    忐忑的一天,心里还是小兴奋的
    atexit()函数
    年终心结,心绪的总结!
  • 原文地址:https://www.cnblogs.com/leee/p/8251512.html
Copyright © 2011-2022 走看看