[英]TypeScript clone self instance with self Class Type
我想克隆當前的類實例並在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()
。 但是,你可以訪問constructor
的性質this
並調用new this.constructor()
有一點皺紋; 因為默認情況下不會編譯,所以TypeScript認為constructor
對象屬性為Function
。 哪個不是new
能力。 這是有原因的。
要使new this.constructor()
在沒有警告的情況下進行編譯,您需要斷言類似new (this.constructor as any)()
,或者使用正確的簽名向State
添加constructor
屬性:
class State
{
"constructor": new() => this; // no-arg polymorphic constructor
public clone():this
{
const state = new this.constructor(); // okay
this._copyData(state);
return state;
}
// etc
}
希望這對你有用。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.