TypeScript使用自类类型克隆自实例
我想克隆当前类实例,并在TypeScript使用自类类型克隆自实例,typescript,polymorphism,clone,Typescript,Polymorphism,Clone,我想克隆当前类实例,并在clone()内部创建多态类的实例,如下所示: class State { public clone():State { const state = new State(); this._copyData(state); return state; } protected _copyData(target:this):void { } } class StateExtend
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);
}
}
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);
}
}
重写State类时,我希望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);
}
}
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);
}
}
但这是行不通的
还有其他建议吗?在运行时
此
只是类的一个实例,而不是类构造函数,因此您不能调用newthis()
。但是您可以访问this
的constructor
属性,并调用newthis.constructor()
有一点皱纹;不会编译,因为默认情况下,TypeScript将构造函数
对象属性视为函数
。这不是新的。这是有原因的
要获得new this.constructor()
在没有警告的情况下编译,您需要像new(this.constructor as any)(
)这样断言类型,或者使用正确的签名将构造函数
属性添加到状态
:
class State
{
"constructor": new() => this; // no-arg polymorphic constructor
public clone():this
{
const state = new this.constructor(); // okay
this._copyData(state);
return state;
}
// etc
}
希望这对你有用。祝你好运 谢谢。“构造函数”:new()=>这个代码>是不需要的。它不需要它就可以编译。TypeScript v2.6.2