【发布时间】:2021-08-03 19:15:57
【问题描述】:
在使用类和子类时,在基类中定义泛型方法并在其中使用实例特定变量是很常见的。
但是,我不知道如何从基类的方法中访问正确的 static 类变量。
以下面的代码为例:
abstract class Unit<T extends Symbol> {
public static factors: {};
constructor(
protected readonly type: T,
protected value: number
) {}
}
class Energy extends Unit<typeof EnergySym> {
public static factors = {
J: 1,
kJ: 1e3,
MJ: 1e6,
GJ: 1e9,
};
constructor(value: number, unit: keyof typeof Energy.factors = 'J') {
super(EnergySym, value * Energy.factors[unit]);
}
get(unit: keyof typeof Energy.factors) {
return this.value / Energy.factors[unit];
}
}
如果我们可以将get 方法放在基类中,通过访问 current 类的静态字段,添加更多类型的单元时需要更少的代码。
在 Python 中,例如,您可以使用 self.__class__.foo。有 JavaScript 等价物吗?
另外,有没有办法为此添加正确的类型?
【问题讨论】:
-
您正在寻找
this.constructor。 (在 TypeScript 类型中,只需this)。 -
顺便说一句,因素只由单位前缀决定,those actually are the same for all SI units.
-
this.constructor根据 Typescript 没有任何属性。除此之外,与打字有关的问题仍未得到解答。 -
在这种情况下,请参阅 stackoverflow.com/questions/33387318/…、stackoverflow.com/questions/32057033/…、stackoverflow.com/questions/29244119/… - TypeScript 缺乏对
this.constructor的支持,但它仍然是正确的方法
标签: javascript typescript inheritance static