【问题标题】:Trace method calls with javascript proxy使用 javascript 代理跟踪方法调用
【发布时间】:2018-08-23 22:06:52
【问题描述】:

var handler1 = {
     get:function(target,key){
         if (typeof target[key] == "function"){
             var method = Reflect.get(target, key);
             return method.bind(target);
         }
     }
}
var handler2 = {
    get: function(target, key){
          if (typeof target[key] == "function"){
            return function(...args){
               var method = Reflect.get(target, key);
               return method.apply(target, args);
            }
          }
     }
}
var proxyObject = new Proxy(window, handler1);
window.obj = function(){console.log("function invoked")};
window.obj.prop = 3; 
var o = proxyObject.obj;
o()// prints "function invoked"
console.log(o.prop) // returns undefined

两个处理程序都可以很好地拦截方法调用,但是在此过程中方法对象上的任何属性都会丢失。有没有办法绑定正确的上下文并在代理返回的对象中保留方法属性。

【问题讨论】:

    标签: javascript javascript-objects es6-proxy


    【解决方案1】:

    这是因为bind创建了一个与原来不同的全新功能:

    function foo(a, b) { return a + b; };
    
    var bar = foo.bind({});
    
    console.log(foo === bar);

    所以在你的处理程序中,不要返回绑定函数,而是返回原始函数:

    var handler = {
        get:function(target,key){
            if (typeof target[key] == "function") {
                return Reflect.get(target, key);                       // return the original function
            }
        }
    }
    
    var proxyObject = new Proxy(window, handler);
    window.obj = function() { console.log("function invoked"); };
    window.obj.prop = 3;
    
    var o = proxyObject.obj;
    o()                                                                // prints "function invoked"
    console.log(o.prop)                                                // returns 3
    console.log(o === window.obj);                                     // true

    【讨论】:

    • 这行不通,因为很多函数在调用时没有正确的上下文。 obj.alert("alert message") 会导致无效调用错误。我们需要在返回函数之前设置正确的this
    • @AyushGoel 正如我所说,绑定创建了一个新函数。如果您真的希望绑定函数具有这些属性,您可以在绑定完成后复制它们,但我认为这不是一个好主意:var boundMethod = ...; Object.assign(boundMethod, originalMethod); return boundMethod;
    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 2013-08-14
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2011-09-04
    • 2014-07-07
    相关资源
    最近更新 更多