December 2016
Intermediate to advanced
841 pages
17h
English
There are scenarios in which only one instance of the specific class should ever exist, and that leads to Singleton Pattern.
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);
}
} ();
Remember that the private modifier only has an effect at compile time, and simply ...
Read now
Unlock full access