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?
The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
Proxy is an object in javascript which wraps an object or a function and monitors it via something called target. Irrespective of the wrapped object or function existence. Proxy are similar to meta programming in other languages.
Traps are internal method detection tools. Whenever you interact with an object, you are calling an essential internal method. Proxies allow you to intercept the execution of a given internal method. So when you run: const profile = {}; profile.
Proxy objects allow you to define get or set traps, which run a function when you attempt to get or set any property to the proxy. The receiver is provided as an argument of that function. The receiver will usually the Proxy object itself, or an object which inherits from it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With