Create a singleton? Why? For the glory of OOP, of course!
ES2022 brings new cool feature of static initializers, which means now it's even easier to create
singletons in JS/TS.
- make constructor private so
scrubsconsumers don't instantiate your class; - create a private static vip-one-of-a-kind instance;
- initialize the vip-one-of-a-kind instance with new ES2022 bells and whistles static block;
- serve the private static vip-one-of-a-kind instance using public static getter
class Foo {
private static instance: Foo;
static {
Foo.instance = new Foo();
}
public static get getInstance(): Foo {
return Foo.instance;
}
private constructor() { }
}
Looks more neat to me than the old way:
class Foo {
private static instance: Foo;
public static get getInstance(): Foo {
if(!Foo.instance){
Foo.instance = new Foo();
}
return Foo.instance;
}
private constructor() { }
}
Though they both are consumed in the same way
const bar = Foo.getInstance;
Huzzah!
Top comments (0)