In this article, you will learn about Singleton Pattern in JavaScript.
There is only one instance of a class and no way to create additional instances of the same class in Singleton Pattern in JavaScript. Singleton objects are typically used in applications to manage global state.
let firebaseInstance = null;
export const getFirebase = () => {
if (firebaseInstance !== null) {
return firebaseIntance;
}
firebase.initializeApp(config);
firebaseInstance = firebase;
return firebaseInstance;
};
Using ES6 Classes
let singletonInstance = null;
class Singleton {
constructor() {
if (!singletonInstance) {
singletonInstance = this;
console.log('Instance created');
}
return singletonInstance;
}
}
const singletonObject = new Singleton();
Using ES7 Classes
class Singleton {
static singletonInstance = null;
static getSingletonInstance() {
if (!Singleton.singletonInstance) {
Singleton.singletonInstance = new Singleton();
console.log('Instance created');
}
return Singleton.singletonInstance;
}
}
const singletonObject = Singleton.getSingletonInstance();
from thetechxp https://ift.tt/2raBeH1
via IFTTT
Comments
Post a Comment