我有一个基类Collection
它提供了基本的数组功能。此类针对其他特定于领域的用例进行了扩展。当像这样的“破坏”方法filter
被调用时,它应该返回一个带有过滤元素的新实例(继续使用类方法而不是仅仅取回数组)。
在 PHP 中你会使用return new self()
返回实际的子类或父类,基于它的构建基础(我认为对于 Java 来说它是return obj.newInstance()
)。但对于 JS/TS,我真的很难找到解决方案。我当前的解决方法是覆盖newInstance
所有子类的方法。
有针对这个的解决方法吗?
class Collection<E> {
protected items: E[];
constructor(items: any[] = []) {
this.items = items;
}
// doesn't work, just one of many attempts
protected newInstance(items: E[]) {
return new Collection(items);
//return new this.constructor(items); // "This expression is not constructable"
// return new this.constructor.prototype(items); // another attempt, says "this.constructor.prototype is not a constructor"
}
size() {
return this.items.length;
}
// should filter and return new instance to use class methods
filter(callback: (item: any, index?: number) => boolean): this {
// should be the actual instance (can be inherited)
return this.newInstance(this.items.filter(callback)) as this;
}
}
class NumberCollection extends Collection<number> {
sum() {
return this.items.reduce((a, b) => a + b, 0);
}
}
let numbers = new NumberCollection([1, 2, 3, 4]);
console.log(numbers.sum()); // works,
// throws "sum() is not a function"
console.log(numbers.filter((n) => n > 1).sum());
要实现类型安全,请使用:
const { constructor } = Object.getPrototypeOf(this);
new constructor(...args);
See 参考同级.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)