Search code examples
ecmascript-6ecmascript-next

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

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.


Solution

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