首页 > 解决方案 > 如何在非静态 getter 中使用“new this”?

问题描述

我正在尝试从静态和常规 getter 中创建父类的新实例。这适用于静态吸气剂,但不适用于常规吸气剂。

class Example {
  static get clone() {
    return new this();
  }
  get clone() {
    return new this();
  }
}

在哪里使用Exampleoverthis工作但导致无法从此类扩展。

class Example {
  static get clone() {
    return new Example();
  }
  get clone() {
    return new Example();
  }
}

如何new this在非静态吸气剂中使用?

标签: typescriptclassinheritanceinstancegetter

解决方案


如果我理解正确,您正在寻找这个:

class Example {
  static get clone() {
    return new this();
  }
  get clone() {
    const copy = new (this.constructor as any)();
    Object.assign(copy, this);
    return copy;
  }
}

用法:

class Foo extends Example {}

console.log(
    Example.clone,
    new Example().clone,
    Foo.clone,
    new Foo().clone
)

推荐阅读