假设有一个类AbstractCollection
可能有许多子类,它们具有类似的构造函数(接受条目)。是否可以在clone()
中实现AbstractCollection
方法,该方法将创建并返回实际子类的新实例,并传入条目?
class AbstractCollection<T> {
constructor(items: T[]) {
// ...
}
clone(): AbstractCollection<T> {
// TODO: implement
}
}
答案 0 :(得分:2)
当然,您正在寻找的是this.constructor
:
class AbstractCollection<T> {
private items: T[];
constructor(items: T[]) {
this.items = items;
}
clone(): AbstractCollection<T> {
return new (this.constructor as { new(items: T[]): AbstractCollection<T>})(this.items);
}
}
然后:
class MyCollection1 extends AbstractCollection<string> {}
class MyCollection2 extends AbstractCollection<number> { }
let a = new MyCollection1(["one", "two", "three"]);
let clonedA = a.clone();
console.log(clonedA); // MyCollection1 {items: ["one", "two", "three"]}
let b = new MyCollection2([1, 2, 3]);
let clonedB = b.clone();
console.log(clonedB); // MyCollection2 {items: [1, 2, 3]}