Constructor code not reachable

帅比萌擦擦* 提交于 2019-12-23 22:08:56

问题


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);
}

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?

Note: I am using babel, so I can use class fields and hence b = new Def() is a valid syntax here.


回答1:


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() {}


来源:https://stackoverflow.com/questions/49599528/constructor-code-not-reachable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!