如何在每个类方法调用之前和之后执行函数?

Sou*_*nda 3 javascript hook class-properties

我想在 javascript 类中的函数上插入预执行和后执行挂钩。

假设我有一堂这样的课。

class Foo {
  method1(p1, p2) {
    this.p1 = p1;
    this.p2 = p2;
  }

  method2(p3) {
    this.p3 = p3;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想为这些预先存在的类方法定义一个 before 和 after 钩子。像这样的东西。

class Foo {
  before(funName, ...params){
    // Should print ('method1', [p1, p2]) when method 1 is called
    // and ('method2', [p3]) when method 2 is called
    console.log(funName, params)
  }
  after(funName, result){
    // Should print the function name followed by its result
    console.log(funName, result)
  }
  method1(p1, p2) {
    this.p1 = p1;
    this.p2 = p2;
  }
  method2(p3) {
    this.p3 = p3;
  }
}

export default Foo;
Run Code Online (Sandbox Code Playgroud)

在对现有代码进行最少更改的情况下实现这些挂钩的最佳方法是什么?

And*_*s_D 5

这是该问题的粗略解决方案:

// we iterate over all method names
Object.getOwnPropertyNames(Foo.prototype).forEach((name) => {

  // First to do: we save the original method. Adding it to prototype
  // is a good idea, we keep 'method1' as '_method1' and so on
  Foo.prototype['_' + name] = Foo.prototype[name];

  // Next, we replace the original method with one that does the logging
  // before and after method execution. 
  Foo.prototype[name] = function() {

    // all arguments that the method receives are in the 'arguments' object
    console.log(`Method call: method1(${Object.values(arguments).join(', ')})`);

    // now we call the original method, _method1, on this with all arguments we received
    // this is probably the most confusing line of code here ;)
    // (I never user this['method'] before - but it works)
    const result = this['_' + name](...arguments);

    // here is the post-execution logging
    console.log(`Method result: ${result}`);

    // and we need to return the original result of the method
    return result;
  };
});
Run Code Online (Sandbox Code Playgroud)

请注意,此代码不是类本身的一部分,请将其作为普通脚本执行。

而且这个简短的概念证明很可能会在现实世界的类上崩溃,并且需要一些额外的检查和特殊情况处理程序,特别是为了获得正确的日志输出。但它适用于你的 Foo 类。

这是工作示例:https://codesandbox.io/s/great-fog-c803c