Skip to content

Instantly share code, notes, and snippets.

@neerajkumar
Created June 11, 2018 10:26
Show Gist options
  • Save neerajkumar/f243abaaa6191e6e1f52ae638aafba83 to your computer and use it in GitHub Desktop.
Save neerajkumar/f243abaaa6191e6e1f52ae638aafba83 to your computer and use it in GitHub Desktop.
Singleton Class - Javascript Solution
var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
(function(global) {
"use strict";
var MySingletonClass = function() {
if ( MySingletonClass.prototype._singletonInstance ) {
return MySingletonClass.prototype._singletonInstance;
}
MySingletonClass.prototype._singletonInstance = this;
this.Foo = function() {
// ...
};
};
var a = new MySingletonClass();
var b = MySingletonClass();
//a === b
global.MySingleton = a; //or b
}(window));
var MySingleton = (function () {
var INSTANCE;
function MySingleton(foo) {
if (!(this instanceof MySingleton)) {
return new MySingleton(foo);
}
this.foo = foo;
}
MySingleton.prototype.bar = function () {
//do something;
};
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;
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment