JSFiddle - React, Tailwind, and code Playground
HTML
it restricts instantiation of a class to a single object
In the event of an instance already existing, it simply returns a reference to that object.
JavaScript
var mySingleton = (function () {
var instance;
function init() {
var someObj = {};
var rand = Math.random();
someObj.getRandomNumber=function() {
return rand;
}
return someObj;
};
return {
getInstance: function () {
// if ( !instance ) {
instance = init();
// return instance;
// }
return instance;
}
};
})();
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log(singleA.getRandomNumber())
console.log(singleB.getRandomNumber())
if( singleA.getRandomNumber() == singleB.getRandomNumber() ){
alert("true")
}// true