我想克隆当前的类实例并在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);
}
}
但这不起作用。
还有其他建议吗?
答案 0 :(得分:4)
在运行时this
只是类的一个实例,而不是类构造函数,因此您无法调用new this()
。但您可以访问constructor
的{{1}}媒体资源并致电this
。
有一点皱纹;默认情况下,TypeScript会将new this.constructor()
对象属性视为constructor
。哪个不是Function
能够的。这有reasons。
要在不发出警告的情况下编译new
,您需要断言类似new this.constructor()
的类型,或者将new (this.constructor as any)()
属性添加到具有正确签名的constructor
:< / p>
State
希望这对你有用。祝你好运!