Inherit execution of static initializer blocks in JavaScript

126 Views Asked by At

I have code like:

class A {
    static {
        console.log("A");
    }
}
class B extends A {
    static {
        console.log("B");
    }
}

Why doesn't it print A twice? I would like a way in JavaScript to execute code of a class whenever it is extended. Is there any way to achieve this?

Of course I could just add a static method in A myself and call it after declaring B, but I wonder if this is already possible via ES2022.

1

There are 1 best solutions below

1
On

Because it is designed like that. The static initializer is only called once for the class that is initialized. It's a big shame though. It would have enabled a subclassing hook in Javascript which is absolutely missing if you want to avoid the use of factory methods.