代码之家  ›  专栏  ›  技术社区  ›  Alex

在javascript中拦截函数调用

  •  3
  • Alex  · 技术社区  · 7 年前

    这个词的意思是什么 __call 来自PHP的神奇方法?

    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 似乎是因为我看到了“get foo”,但是 apply 没有。我得到的不是一个函数错误。

    3 回复  |  直到 7 年前
        1
  •  8
  •   Aurel Bílý    7 年前

    apply 到对象本身 new Proxy(someFunction, { 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));
        2
  •  2
  •   Badis Merabet    7 年前

    这是实现您要求的另一种方式。

    class MyClass{
      constructor(){
         return new Proxy(this, {
            get(target, propKey, receiver) {
                const origMethod = target[propKey];
                return function (...args) {
                    let result = origMethod.apply(this, args);
                    console.log(propKey + JSON.stringify(args)
                        + ' -> ' + JSON.stringify(result));
                    return result;
                };
            }
        });
      }
      
    foo = (x) => {
      return x + 1;
    };
    
    }
    
    var inst = new MyClass();
    console.log(inst.foo(123));
        3
  •  2
  •   quirimmo    7 年前

    get

    然后在这里我也执行了你的真实方法,但我不知道你是否想模仿它。

    class MyClass {
      constructor() {
        return new Proxy(this, {
          get(target, prop, receiver) {
            if (typeof target[prop] !== "function") {
              return "etcetcetc";
            }
            return function(...args) {
              console.log('call', args);
              return target[prop]();
            };
          }
        });
      }
    
      foo() {
        console.log('I am foo!');
      }
    }
    
    var inst = new MyClass();
    inst.foo(123);

    如您所见,如果您正在调用实例的方法,我将拦截它,然后返回您最初的方法执行。

    如果您正在访问实例的属性,我将始终返回模拟字符串。

    推荐文章