Why is my function proxy not being called in Node?

大城市里の小女人 提交于 2021-01-19 06:00:02

问题


I was using proxy get method fine. Then I tried using it on a function and quickly realized I needed to use the apply method. This simple example is not working. It never enters apply.

Node looks to support apply https://node.green/#ES2015-built-ins-Proxy--apply--handler. Not sure what I'm doing wrong.

var Foo = {
  runme: function() {
    return 1;
  }
};

var Magic = {
  Foo: Foo
};

Magic.Foo = new Proxy(Object.assign({}, Magic.Foo), {
  apply: function(target, thisArg, argumentsList) {
    // never gets in here
    console.log('Proxying function call');
    console.log(target);
    return 2;
  }
});

console.log(Foo.runme()); // outputs 1
console.log(Magic.Foo.runme()); // outputs 1

I tried both Proxy on Magic.foo directly and via the Object.assign to see if it needed to be its own object or not. Neither worked.


回答1:


You assume here that apply traps work like get traps -- i.e., for any property of the proxied object -- but they do not. The apply trap runs when the Proxy itself is called a function. Here, your proxy is Magic.Foo, but you never call Magic.Foo(). You only call Magic.Foo.runme(), which is not a proxied function.

You must wrap each function whose invocation you wish to intercept in its own individual Proxy wrapper.

Alternatively, you could use a get trap on Magic.Foo that returns a function with the appropriate behavior for each accessed property.




回答2:


The apply trap only applies to proxies over functions, which create callable objects (i.e. functions). A new Proxy created on a normal object (like your {}) creates a non-callable proxy object, which will never trigger apply.



来源:https://stackoverflow.com/questions/49884736/why-is-my-function-proxy-not-being-called-in-node

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