4 ms·
Singletons in JS/TS are done by creating and exporting an instance of a class: class MyClass {} export const myClassSingleton = new MyClass() Static initi
by gavinray 5y ago
Singletons in JS/TS are done by creating and exporting an instance of a class:
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);
- officialchicken 5y agoThat's pretty close, but you need to add the protections around Object.keys(...) with guards in the getters and setters when using JS/TS. Sealing the entire class static should prevent the need and ability to edit that way.