有人可以帮我理解为什么在 Typescript 中从属性方法访问静态成员是错误的吗?它在普通 ES6 中工作正常,并且作为适当的原型方法。
class FooBar {
static v = 123;
static foo = () => this.v; // this is an error in TS (but ok in ES6)
static bar() {
return this.v; // but this is ok in TS??
}
}
Run Code Online (Sandbox Code Playgroud)
这是错误,它似乎将函数体中的代码视为属性初始值设定项本身:
apptest2.ts:40:24 - error TS2334: 'this' cannot be referenced in a static property initializer.
40 static foo = () => this.v;
~~~~
Run Code Online (Sandbox Code Playgroud)
如果代码更像是,则错误是有意义的static foo = this.v,但作为函数回调的一部分,将其视为类的初始化阶段的一部分是没有意义的,this无法定义......无论如何,这也适用于ES6这让我更加困惑为什么这是一个错误以及为什么它bar()在foo().
我今天遇到了这个问题,我注意到以下几点:
如果您使用箭头函数,您需要引用ClassName而不是this
class FooBar {
static v = 123;
static fooArrow = () => FooBar.v; //works
static foo () {this.v}; //works
}
Run Code Online (Sandbox Code Playgroud)
这似乎是 Typescript 中的一个已知问题,并且已经就可能的修复方案进行了长期讨论。我认为由于上下文如何绑定的问题,暂时避免类中的箭头函数是个好主意this。
| 归档时间: |
|
| 查看次数: |
1716 次 |
| 最近记录: |