Skip to content

Comment on Deno 1.14parent

Comments

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

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);

That'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.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.