Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept function calls in javascript

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.

like image 205
Alex Avatar asked Jan 13 '19 18:01

Alex


People also ask

What is intercepting function calls?

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.

What is intercept in Javascript?

Interceptors are code blocks that you can use to preprocess or post-process HTTP calls, helping with global error handling, authentication, logging, and more.


1 Answers

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));
like image 142
Aurel Bílý Avatar answered Sep 20 '22 02:09

Aurel Bílý