javascriptstaticstatic-block

Can't access static methods from outside until JavaScript's static block is over?


class B {
    foo() {
        return A.foo(); // message: Uncaught ReferenceError: A is not defined
    }
}
class A {
    static {
        console.log(new B().foo());
    }

    static foo() {
        return "foo";
    }
}

I expected the "foo" to be called, but I can't even access A class. Isn't the A class declared when the static block works?


Solution

  • According to MDN, static blocks...

    allow statements to be evaluated during initialization, which allows initializations that (for example) include try...catch or set multiple fields from a single value.

    These blocks are evaluated during the initialization of the class, and therefore, the class is not initialized, nor is it defined yet; hence the error.

    So in conclusion, the behavior you are seeing is expected. That also explains why moving the static block down (after the foo method) does not fix the error, and also why this.foo() works but new B().foo() does not,

    class B {
        foo() {
            return A.foo(); // message: Uncaught ReferenceError: A is not defined
        }
    }
    
    class A {
        static foo() {
            return "foo";
        }
        
        static {
            console.log(this.foo());    // ok
            console.log(new B().foo()); // errors
        }
    }

    ... given this (also from MDN).

    Initialization is performed in the context of the current class declaration, with privileged access to private state.