Why is my function proxy not being called in Node?

前端 未结 2 712
深忆病人
深忆病人 2021-01-14 09:57

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 i

相关标签:
2条回答
  • 2021-01-14 10:43

    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.

    0 讨论(0)
  • 2021-01-14 10:52

    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.

    0 讨论(0)
提交回复
热议问题