3

I was using proxy get method fine. Then I tried using it on a function and quickly realized I needed to use the apply method. This simple example is not working. It never enters apply.

Node looks to support apply https://node.green/#ES2015-built-ins-Proxy--apply--handler. Not sure what I'm doing wrong.

var Foo = {
  runme: function() {
    return 1;
  }
};

var Magic = {
  Foo: Foo
};

Magic.Foo = new Proxy(Object.assign({}, Magic.Foo), {
  apply: function(target, thisArg, argumentsList) {
    // never gets in here
    console.log('Proxying function call');
    console.log(target);
    return 2;
  }
});

console.log(Foo.runme()); // outputs 1
console.log(Magic.Foo.runme()); // outputs 1

I tried both Proxy on Magic.foo directly and via the Object.assign to see if it needed to be its own object or not. Neither worked.

Dave Stein
  • 8,653
  • 13
  • 56
  • 104
  • Yes, you should be using the `get` trap to capture `Magic.Foo.runme` accesses. Please show us your attempt and explain how it did not work. – Bergi Apr 17 '18 at 18:41
  • http://2ality.com/2015/10/intercepting-method-calls.html – Bergi Apr 17 '18 at 18:46

2 Answers2

2

You assume here that apply traps work like get traps -- i.e., for any property of the proxied object -- but they do not. The apply trap runs when the Proxy itself is called a function. Here, your proxy is Magic.Foo, but you never call Magic.Foo(). You only call Magic.Foo.runme(), which is not a proxied function.

You must wrap each function whose invocation you wish to intercept in its own individual Proxy wrapper.

Alternatively, you could use a get trap on Magic.Foo that returns a function with the appropriate behavior for each accessed property.

apsillers
  • 112,806
  • 17
  • 235
  • 239
1

The apply trap only applies to proxies over functions, which create callable objects (i.e. functions). A new Proxy created on a normal object (like your {}) creates a non-callable proxy object, which will never trigger apply.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375