There's probably a use-case I'm missing, because intuitively I'd automatically classify it as bad a practice.
There's probably a use-case I'm missing, because intuitively I'd automatically classify it as bad a practice.
Yes and no. For example, maybe you want to initialise a temporary directory on the filesystem for writing files to, for some caching mechanism. The pointer to the cache directory (maybe a const x = {}) can exist anywhere, but spinning up the directory itself in the static class block ensures that it's set up once and only once for all instances of the class. So, any instances get to reuse the directory without worrying about checking for initialisation first.
Just another tool in the toolbox, best evaluated on a case-by-case basis
There's a better example here: https://v8.dev/features/class-static-initializer-blocks
You could also use it for initialising generated constants.
class MyClass {}
export const myClassSingleton = new MyClass()
Static initialization blocks = "Constructors, for static class members/values"Static blocks only run once, like the class declaration itself:
class User {
constructor(public name: string, public age: number) {}
static {
console.log("Hello from class User static block")
}
}
const a = new User("a", 1)
const b = new User("b", 2)
Is transpiled to: class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
(() => {
console.log("Hello from class User static block");
})();
const a = new User("a", 1);
const b = new User("b", 2);I guess it's a good way to bring back that behavior with the added bonus of being useful by itself in some limited but legitimate cases (sibiling comment mentioned cache initialization, also a good point).
module.exports =
class MyClass
{ // ...
static init ()
{ // ... do something, like create and
// cache a Singleton etc.
return this;
}
} . init();
The static method init() is executed only once when the class is created and exported. You could add some check to it that causes an error if it gets called more than once.Do static blocks allow me to do something more?
It seems like a minor convenience, but it might play well with inheritance or mixin classes?