Can't set “apply” trap to Proxy object

前端 未结 1 790
挽巷
挽巷 2020-12-09 12:12

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

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


        
相关标签:
1条回答
  • 2020-12-09 12:44

    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.

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