What's the equivalent of the __call magic method from PHP ?
I was under the impression that Proxy can do this, but it can't.
class MyClass{
  constructor(){
    return new Proxy(this, {
      apply: function(target, thisArg, args){
        console.log('call', thisArg, args);
        return 'test';
      },
      get: function(target, prop){
        console.log('get', prop, arguments);
      }
    });
  }
}
var inst = new MyClass();
console.log(inst.foo(123));
get seems to work because I see "get foo", but apply does not. I get is not a function error.
Function call interception (FCI), or method call interception (MCI) in the object-oriented programming domain, is a technique of intercepting function calls at program runtime.
Interceptors are code blocks that you can use to preprocess or post-process HTTP calls, helping with global error handling, authentication, logging, and more.
apply actually handles a function call to the object itself, i.e. if you do new Proxy(someFunction, { apply: ... }), apply would be called before someFunction is called.
There is nothing for trapping a call to a property, because this would be superfluous – get already handles when a property is returned. You can simply return a function that then produces some debug output when called.
class MyClass{
  constructor(){
    return new Proxy(this, {
      get: function(target, prop) {
        return function() {
          console.log('function call', prop, arguments);
          return 42;
        };
      }
    });
  }
}
var inst = new MyClass();
console.log(inst.foo(123));
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