Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set "apply" trap to Proxy object

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?

like image 410
Oriol Avatar asked Sep 02 '15 18:09

Oriol


People also ask

What does a proxy do to the target object 1 point?

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.

What is proxy object in Javascript?

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.

What is trap in Javascript?

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.

What is receiver in proxy?

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.


1 Answers

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.

like image 110
Oriol Avatar answered Oct 12 '22 12:10

Oriol