3 ms·
Off the top of my head it's probably useful for implementing The Singleton Pattern, which reduces to one single instance of a class: https://en.wikipedia.org/w
by officialchicken 5y ago
Off the top of my head it's probably useful for implementing The Singleton Pattern, which reduces to one single instance of a class: https://en.wikipedia.org/wiki/Singleton_pattern https://en.wikipedia.org/wiki/Singleton_pattern
- gavinray 5y agoSingletons 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.