Nis*_*eph 3 polymorphism clone typescript
我想克隆当前的类实例,并在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);
}
}
Run Code Online (Sandbox Code Playgroud)
覆盖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);
}
}
Run Code Online (Sandbox Code Playgroud)
但这是行不通的。
还有其他建议吗?
在运行时this只是类的实例,而不是类构造函数,因此您不能调用new this()。但是,你可以访问constructor的属性this和调用new this.constructor()。
有一点皱纹;由于默认情况下不会编译,因此TypeScript认为constructorobject属性为Function。哪一个不行new。这是有原因的。
要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
}
Run Code Online (Sandbox Code Playgroud)
希望对您有用。祝好运!
| 归档时间: |
|
| 查看次数: |
424 次 |
| 最近记录: |