我在JavaScript中使用了下面给出的实现。
class Base {
installGetters() {
Object.defineProperty(this, 'add', {
get() {
return 5;
}
});
}
}
class New extends Base {
constructor() {
super();
this.installGetters();
}
someAddition() {
return 10 + this.add;
}
}
我在父类函数Base
中定义了getter属性add
,并在子类构造函数中调用installGetters()
函数后,在子类New
中使用了该属性。这在JavaScript中有效,但在TypeScript中会导致this.add
出错。希望能得到帮助。
我这么做的主要动机是想将一个对象传递给installGetters()
函数,以便它可以生成多个getter,其中对象键是getter名称,而值则来自相应的getter函数。
这在JavaScript中是有效的,因此我的主要好奇心是这是否不可能在TypeScript中实现,还是我做错了什么。
Base
类中使用get add()
呢?为什么要用Object.defineProperty
进行赋值?installGetters()
的实际作用是什么? - VLAZinstallGetters()
,它可以创建多个getter,其中键作为getter名称,值作为返回值。 - Sayantan Ghosh