在javascript中拦截函数调用

Ale*_*lex 5 javascript proxy function node.js

__callPHP中的魔法方法的等价物是什么?

我的印象是 Proxy 可以做到这一点,但它不能。

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));
Run Code Online (Sandbox Code Playgroud)

get似乎有效,因为我看到“get foo”,但apply没有。我得到的不是函数错误。

Aur*_*ílý 7

apply实际上处理对对象本身的函数调用,即如果你这样做new Proxy(someFunction, { apply: ... })apply会在被调用之前someFunction被调用。

没有什么可以捕获对属性的调用,因为这是多余的——get在返回属性时已经处理了。您可以简单地返回一个函数,然后在调用时产生一些调试输出。

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));
Run Code Online (Sandbox Code Playgroud)