【问题标题】:How can I use `new this` within a non-static getter?如何在非静态 getter 中使用“new this”?
【发布时间】:2020-07-20 15:01:48
【问题描述】:

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

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

this 上使用Example 有效但导致无法从此类扩展。

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

如何在非静态 getter 中使用 new this

【问题讨论】:

    标签: typescript class inheritance instance getter


    【解决方案1】:

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

    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
    )
    

    【讨论】:

    • 只需要return copy as this
    猜你喜欢
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    相关资源
    最近更新 更多