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?
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