class - 编写 TypeScript 装饰器以始终将类方法绑定(bind)到 'this'

标签 class typescript scope decorator abstract

我正在尝试编写一个装饰器来始终将类方法的范围绑定(bind)到该类的实例。

这是我迄今为止的实现:

function LockThis<T extends { new(...args: any[]): {} }>(constructor: T) {
  let self: any;
  const locker = class extends constructor {
    constructor(...args: any[]) {
      super(...args);
      self = this;
    }
  };
  const proto = constructor.prototype;
  Object.getOwnPropertyNames(proto).forEach(key => {
    if (key === 'constructor') {
      return;
    }
    const descriptor = Object.getOwnPropertyDescriptor(proto, key);
    if (descriptor && typeof descriptor.value === 'function') {
      const original = descriptor.value;
      locker.prototype[key] = (...a: any[]) => original.apply(self, a);
    }
  });
  return locker;
}

@LockThis
class Something {
  private foo = 'bar';

  public doIt(someVar?: string) {
    return this.foo + ' ' + someVar;
  }
}

const something = new Something();
console.log(something.doIt.call({}, 'test'));
--> bar test

这有效,除了抽象类:

@LockThis
abstract class Blah {

}

TS2345: Argument of type 'typeof Blah' is not assignable to parameter of type 'new (...args: any[]) => {}'.
  Cannot assign an abstract constructor type to a non-abstract constructor type.

是否有不同的类型保护来允许实际类和抽象类和/或按方法执行此操作的方法?

(我对每个方法的尝试都是徒劳的,因为在调用该方法之前我似乎无法确定“this”,如果使用不同的范围调用则为时已晚)

class Something {
  private foo = 'bar';

  @LockThis()
  public doIt(someVar?: string) {
    return this.stuff + ' ' + someVar;
  }
}

最佳答案

根据Microsoft/TypeScript#5843 ,没有很好的方法来引用抽象构造函数类型。那里提到的解决方法是仅使用 Function,这太宽松了(并非所有函数都是构造函数),但可能对您有用,因为您不太可能尝试在随机函数。

并且您无法在Function上进行混合,因此实现仍然需要认为您有一个构造函数。因此我建议您使用 function overloadLockThis 上,以便调用者看到 Function 但实现仍然看到它可以扩展的构造函数。例如:

// callers see a function that takes any function and returns the same type
function LockThis<T extends Function>(constructor: T): T;

// implementation is unchanged, and still sees a (concrete) constructor
function LockThis<T extends { new(...args: any[]): {} }>(constructor: T) {
  // ... your unchanged implementation here
}

现在可以了:

@LockThis // no error
abstract class Blah { } 

这是我能得到的最接近你想要的东西。希望有帮助;祝你好运!

关于class - 编写 TypeScript 装饰器以始终将类方法绑定(bind)到 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910712/

相关文章:

java - 如何组织 Java 文本冒险的类和列表

reactjs - 接口(interface) A 错误地扩展了接口(interface) B

typescript - 同步gradle后IntelliJ WAR Artifact缺少文件夹

c++ - esms.cpp :234: error: 'the_config' was not declared in this scope

c++ - 在类成员中调用函数 (C++)

javascript - 删除 JavaScript 对象的实例

c++ - 在函数中销毁局部变量是什么意思

addEventListener 匿名函数中的 Javascript 变量范围

c++ - "Undefined Symbols"但函数已定义和声明,没有拼写错误

javascript - 使用递归和 yield 关键字提取嵌套列表的 Typescript 函数