构造函数代码不可访问 [英] Constructor code not reachable
问题描述
我正在将类方法作为参数传递给这样的新类实例:
I am passing a class method as a parameter to a new class instantiation like this:
class Abc {
constructor() {
this.a = () => { };
}
b = new Def(this.a);
}
我在浏览器控制台中得到无法读取未定义的属性a".为什么在 b = new Def(this.a)
中的 a
undefined
是未定义的?在调试时,我发现浏览器抛出错误,并且构造函数代码从未到达.为什么会这样?
I get 'cannot read property a of undefined' in browser console. Why is a
undefined
inside b = new Def(this.a)
? On debugging, I found that browser throws the error and the constructor code is never reached. Why is this happening?
注意:我正在使用babel,所以我可以使用类字段,因此 b = new Def()
是有效的语法.
Note: I am using babel, so I can use class fields and hence b = new Def()
is a valid syntax here.
推荐答案
这是类字段的工作方式,它们在构造函数主体之前(但在 super()
之后)进行求值.第1行在第2行之前求值,而构造函数和 b
字段的顺序无关紧要:
That's how class fields work, they are evaluated before constructor body (but after super()
). Line 1 is evaluated before line 2, and the order in which constructor and b
field are ordered doesn't matter:
constructor() {
this.a = () => { }; // 2
}
b = new Def(this.a); // 1
由于类字段已经在使用中,为了维持正确的执行顺序,它应该是:
Since class fields are already in use, in order to maintain proper execution order it should be:
a = () => { }; // 1
b = new Def(this.a); // 2
constructor() {}
这篇关于构造函数代码不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!