Can't set “apply” trap to Proxy object

白昼怎懂夜的黑 提交于 2019-11-27 02:17:37

问题


I created a Proxy object with an "apply" trap:

var target = {},
    handler = { apply: () => 42 }
    proxy = new Proxy(target, handler);

Therefore, the Proxy object should be callable. However, it doesn't work:

proxy(); // TypeError: proxy is not a function

Why?


回答1:


According to the definition of the [[Call]] internal method of Proxy objects it should work:

  • Let trap be GetMethod(handler, "apply").
  • Return Call(trap, handler, «target, thisArgument, CreateArrayFromList(argumentsList)»).

However, there is a problem: not all Proxy objects have the [[Call]] method:

A Proxy exotic object only has a [[Call]] internal method if the initial value of its [[ProxyTarget]] internal slot is an object that has a [[Call]] internal method.

Therefore, the target must be a function object:

var target = () => {},
    handler = { apply: () => 42 }
    proxy = new Proxy(target, handler);
proxy(); // 42

Note that I defined target using an arrow function in order to create a function object which is not a constructor function. This way the Proxy object can be called but not instantiated.

If you want to add a "construct" trap too, the target must have a [[Construct]] method, so define it with a function declaration or function expression.



来源:https://stackoverflow.com/questions/32360218/cant-set-apply-trap-to-proxy-object

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