javascript - 使用 MethodDecorator 更改函数的参数,而不更改 "this value"?

标签 javascript typescript ecmascript-6 typescript-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: Cannot read property 'qux' of null

这里的问题是apply(null, args),它改变了this的上下文。这使得无法从 foo() 内部调用名为 qux 的实例变量。

另一种可能性是将调用更改为originalMethod.apply(target, args),但这次quxundefined,而bar() 可以被调用。

是否有可能在将 this 上下文正确设置为实例的情况下调用 originalMethod

最佳答案

使用 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;
  }
};

关于javascript - 使用 MethodDecorator 更改函数的参数,而不更改 "this value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105906/

相关文章:

javascript - 为什么javascript中的nextSibling方法不能正常工作

javascript - 使用Javascript使图像在页面打开时可见

javascript - 为什么 TypeScript 允许在方法中省略 "this"?

javascript - typescript :生成文件中的连接顺序

javascript - 使用变量设置类的属性

javascript - 如何组合两个键名称不同但对应值相同的对象数组?

javascript - 为什么 jQuery 必须接收 2 个对象 : body & html when scrolling whole page with animation?

javascript - GWT HTTP 响应 getText() 作为二进制

angular - 在 Angular 5 中将数据从服务获取到 react 形式的最佳方式

javascript - JavaScript ES6 中的解构对象函数