我想克隆当前的类实例并在 clone()
中创建一个多态类的实例,如下所示:
class State
{
public clone():State
{
const state = new State();
this._copyData(state);
return state;
}
protected _copyData(target:this):void
{
}
}
class StateExtends extends State
{
public clone():StateExtends
{
const state = new StateExtends();
return state;
}
protected _copyData(target:this):void
{
super._copyData(target);
}
}
当覆盖 State 类时,我希望 clone()
签名在所有类层次结构中保持相同。我可以做这样的事情吗:
class State
{
public clone():this
{
const state = new this();
this._copyData(state);
return state;
}
protected _copyData(target:this):void
{
}
}
class StateExtends extends State
{
protected _copyData(target:this):void
{
super._copyData(target);
}
}
但这行不通。
还有什么建议吗?
最佳答案
在运行时this
只是类的实例,不是类的构造器,所以不能调用new this()
。但是您可以访问 this
的 constructor
属性并调用 new this.constructor()
。
有一点皱纹;不会编译,因为默认情况下,TypeScript 将 constructor
对象属性视为 Function
。这不是新的
。有reasons为此。
要让 new this.constructor()
在没有警告的情况下进行编译,您需要断言像 new (this.constructor as any)()
这样的类型,或者使用正确的签名将 constructor
属性添加到 State
:
class State
{
"constructor": new() => this; // no-arg polymorphic constructor
public clone():this
{
const state = new this.constructor(); // okay
this._copyData(state);
return state;
}
// etc
}
希望这对您有用。祝你好运!
关于带有自身类类型的 TypeScript 克隆自身实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47858075/