Often times we would want to limit number of instances of a class to 1. We can achieve this using the following pattern. You can use Object.freeze() to prevent further modifications of an object.
// Using ES6 Classes.
class Singleton {
static getInstance() {
if (!this.instance) {
this.instance = new Object('Test');
}
return this.instance;
}
}
console.log(Singleton.getInstance() === Singleton.getInstance());
// true
// Using functions.
function SingletonWrapper() {
let instance;
return {
getInstance: function() {
if (!instance) {
instance = new Object('Test');
}
return instance;
}
}
}
const singletonWrapper = SingletonWrapper();
console.log(singletonWrapper.getInstance() === singletonWrapper.getInstance());
// true