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

使用MethodDecorator更改函数的参数,而不更改“this value”?

  •  0
  • gremo  · 技术社区  · 7 年前

    想象一下你必须 更改方法参数 在运行时,使用decorator。一个简单的例子:所有参数都设置为“Hello World”:

    export const SillyArguments = (): MethodDecorator => {
      return (
          target: Object,
          propertyKey: string | symbol,
          descriptor: PropertyDescriptor
      ) => {
        const originalMethod = descriptor.value;
        descriptor.value = (...args: any[]) => {
          Object.keys(args).forEach(i => {
            args[i] = 'Hello World';
          });
    
          return originalMethod.apply(null, args);
        };
    
        return descriptor;
      }
    };
    

    用法示例:

    class TestClass {
      private qux = 'qux';
    
      @SillyArguments()
      foo(val: any) {
        console.log(val);
        console.log(this.qux);
        this.bar();
      }
    
      bar() {
        console.log('bar');
      }
    }
    
    const test = new TestClass();
    test.foo('Ciao mondo'); // prints "Hello World"
    

    TypeError:无法读取null的属性“qux”

    apply(null, args) this . 这使得调用名为 qux ,从内部 foo()

    另一种可能是将呼叫改为 originalMethod.apply(target, args) ,但这次 库克斯 undefined ,而 bar() 可以调用。

    有没有可能调用 originalMethod

    1 回复  |  直到 7 年前
        1
  •  1
  •   Matt McCutchen    7 年前

    使用 function 函数而不是箭头函数,以便接收原始 this

    export const SillyArguments = (): MethodDecorator => {
      return (
          target: Object,
          propertyKey: string | symbol,
          descriptor: PropertyDescriptor
      ) => {
        const originalMethod = descriptor.value;
        descriptor.value = function (...args: any[]) {
          Object.keys(args).forEach(i => {
            args[i] = 'Hello World';
          });
    
          return originalMethod.apply(this, args);
        };
    
        return descriptor;
      }
    };