O'Reilly logo

TypeScript Design Patterns by Vilic Vane

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Singleton

There are scenarios in which only one instance of the specific class should ever exist, and that leads to Singleton Pattern.

Basic implementations

The simplest singleton in JavaScript is an object literal; it provides a quick and cheap way to create a unique object:

const singleton = { 
  foo(): void { 
    console.log('bar'); 
  } 
}; 

But sometimes we might want private variables:

const singleton = (() => { 
  let bar = 'bar'; 
   
  return { 
    foo(): void { 
      console.log(bar); 
    } 
  }; 
})(); 

Or we want to take the advantage of an anonymous constructor function or class expression in ES6:

const singleton = new class { 
  private _bar = 'bar'; 
   
  foo(): void { 
    console.log(this._bar); 
  } 
} (); 

Note

Remember that the private modifier only has an effect at compile time, and simply ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required