How to create a singleton class - kdaisho/Blog GitHub Wiki

What is singleton?

A singleton is a design pattern that ensures a class has only one instance and provides a global point of access to that instance.

Singleton class example

class TodoList {
  #data = new Set()

  get items() {
    return this.#data
  }

  constructor() {
    if (TodoList.instance) {
      throw new Error("Use TodoList.getInstance() to access the list")
    }
  }

  static instance = null
  
  static {
    this.instance = new TodoList()
  }
  
  static getInstance() {
    return this.instance
  }
}

So you cannot instantiate as it is done when the class was defined. The static initialization block static { ... } immediately runs when the class is defined.

const todo = TodoList.getInstance()

const todo2 = new TodoList() // throws error