JSFiddle - React, Tailwind, and code Playground
JavaScript
// Using ES6 Classes.
class Singleton {
static getInstance() {
if (!this.instance) {
this.instance = new Object('Test');
}
return this.instance;
}
}
console.log(Singleton.getInstance() === Singleton.getInstance());
// 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());