Skip to content

Instantly share code, notes, and snippets.

@thegitfather
Last active July 13, 2021 14:09
Show Gist options
  • Save thegitfather/2d204637eb6b62af171d to your computer and use it in GitHub Desktop.
Save thegitfather/2d204637eb6b62af171d to your computer and use it in GitHub Desktop.
singleton pattern
/*
* http://blog.mgechev.com/2014/04/16/singleton-in-javascript/
*
* - It instantiates only a single object
* - Its safe – it keeps the reference to the singleton inside a variable, which
* lives inside a lexical closure and is not accessible by the outside world
* - It allows you to initialize the singleton with some arguments. The module
* pattern, which wraps the singleton is not aware of the initialization
* arguments – it simply forwards the call with apply
* - You can use the instanceof operator
*
*/
var MySingleton = (function () {
var INSTANCE;
function MySingleton(foo) {
if (!(this instanceof MySingleton)) {
return new MySingleton(foo);
}
this.foo = foo;
}
MySingleton.prototype.bar = function () {
console.log("bar(): this.foo:", this.foo);
};
MySingleton.prototype.setBar = function (val) {
this.foo = val;
};
return {
init: function () {
if (!INSTANCE) {
return INSTANCE = MySingleton.apply(null, arguments);
}
return INSTANCE;
},
getInstance: function () {
if (!INSTANCE) {
return this.init.apply(this, arguments);
}
return INSTANCE;
}
};
}());
(function() {
"use strict";
var myObj = MySingleton.init('example');
myObj.bar();
var myObj2 = MySingleton.init('example2');
myObj2.bar();
var myObj3 = MySingleton.getInstance();
myObj3.bar();
myObj.setBar("EXAMPLE");
myObj.bar();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment