【发布时间】:2017-09-07 15:22:17
【问题描述】:
我想创建一个从 Array 派生的新类,除了常规的数组方法外,它还有自己的方法。
export class ObjectCollection<T extends Iidentifier> extends Array<T> {
constructor(collection: T[] = []) {
super(...collection);
}
// used for getting instance from a collection of objects
public getInstance(id: Id) {
return this.find(item => item.Id.toString() === id.toString()) || new
Array<T>();
}
}
我也有继承自该类的子类。
export class TargetCategories extends ObjectCollection<TargetCategory> {
constructor(categories: TargetCategory[] = []) {
super(categories);
}
public getCategoryType(id: Iidentifier): string {
return this[id].Category.length < 2 ? "dummy" : "saved";
}
}
当我实例化一个 TargetCategories 对象时,我只能使用数组中的方法。我无法调用 getCategoryType 和 getInstance 之类的东西。
【问题讨论】:
-
在运行时还是在编译时?你遇到了什么错误 ?您如何创建和使用 TargetCategories 的实例?
-
我用全新的 TargetCategories() 进行了尝试,但仍然无法从实例中访问这些方法。我可以访问方法的唯一方法是,如果我像使用类方法一样使用它,例如 TargetCategories.prototype.say
-
是编译时错误还是运行时错误?你能分享你的代码吗?我使用了你的代码,填写了缺失的部分,它可以在 chrome 中运行、编译和运行。
-
运行时错误。常量目标 = 新 ObjectCollection
(); console.log(target.indexOf(new TargetCategory())); console.log(ObjectCollection.prototype.say()); console.log(target.say());它将在最后一个失败。 -
你要转换成什么?
标签: javascript typescript ecmascript-6 prototypal-inheritance