我认为这是有充分理由的,但对我来说这似乎很奇怪。请以以下代码为例说明问题。
class Foo {
constructor(referenceMethod: () => void) {
}
}
class Bar extends Foo {
TestProperty: string = "boo";
constructor() {
super(this.ReferenceMethod);
}
ReferenceMethod() {
}
}
这会产生编译错误
'this' cannot be referenced in current location.
如果我们在构造函数中初始化 TestProperty
,编译器会很高兴并且世界会按预期旋转,当然如果我们不将对 referenceMethod 的引用传递给我们可以设置的 super 调用构造函数外的 TestProperty 没问题。
但是我只是不明白为什么同时做这两件事会导致问题。如果有人能阐明这一点以帮助我理解,将不胜感激。
最佳答案
来自 Typescript language specification 的 8.3.2 :
The first statement in the body of a constructor must be a super call if both of the following are true: 1. The containing class is a derived class.
2. The constructor declares parameter properties or the containing class declares instance member variables with initializers.
示例中的包含类声明了一个名为 TestProperty
的变量,该变量使用了初始化程序:
TestProperty: string = "boo";
你看到错误的原因是编译器要求 constructor
的第一行是对 super
的调用,给定你的当前布局类(上面语言规范中的#2)。因此,这意味着当您开始引用类的属性(如 TestProperty
)时,该类未完全初始化。虽然 ReferenceMethod
将被初始化并可用,但成员变量仍然不会,这可能会破坏您类中的其他功能。
虽然语言作者可以生成可避免此问题的工作代码,但如果按照您所发现的方式工作,显然会更容易、更一致。
作为替代方案,您可以尝试添加一个 initialize
方法,该方法在构造函数完全初始化类后执行相同的逻辑。诚然,这是第二步,但它适用于 TypeScript。但是,请注意确保 在构造函数初始化成员变量后调用 initialize。
关于typescript - 奇怪的 Typescript 编译器错误 : 'this' cannot be referenced in current location, 谁能解释一下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857275/