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 disappears after being compiled to JavaScript (although of course its accessibility will be kept in .d.ts
).
However, it is possible to have the...