typescript - 如何在非静态 getter 中使用“new this”?
问题描述
我正在尝试从静态和常规 getter 中创建父类的新实例。这适用于静态吸气剂,但不适用于常规吸气剂。
class Example {
static get clone() {
return new this();
}
get clone() {
return new this();
}
}
在哪里使用Example
overthis
工作但导致无法从此类扩展。
class Example {
static get clone() {
return new Example();
}
get clone() {
return new Example();
}
}
如何new this
在非静态吸气剂中使用?
解决方案
如果我理解正确,您正在寻找这个:
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
)
推荐阅读
- c - 释放内存(或分配)的问题
- oracle - oracle修改全局临时表
- ibm-midrange - IBM i- 将 IFS 文本文件中的数据解析为 IBM i db2 表?
- c# - 在 .net 核心中设置全球时区
- jquery - Ruby 瘦服务器 ActionView::Template 错误
- android - BottomSheetDialogFragment 允许用户触摸外部
- javascript - 具有成功和拒绝功能的承诺链
- java - 如何使用 jOOQ RecordUnmapper?
- php - MYSQL 减少多个子查询的执行时间
- jquery - 无法读取未定义的属性长度(空容器警报消息)