Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Last active May 5, 2017 11:55
Show Gist options
  • Select an option

  • Save YozhEzhi/0d9c1c1770b06a84a87656f91d8ce8d8 to your computer and use it in GitHub Desktop.

Select an option

Save YozhEzhi/0d9c1c1770b06a84a87656f91d8ce8d8 to your computer and use it in GitHub Desktop.
var mySingleton = (function () {
var instance;
function init() {
function privateMethod() {
console.log( "I am private" );
}
var privateVariable = "Im also private";
return {
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getPrivateVariable: function() {
return privateVariable;
}
};
}
return {
getInstance: function () {
if (instance) return instance;
instance = init();
return instance;
}
};
})();
// Usage:
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log(singleA.getPrivateVariable() === singleB.getPrivateVariable()); // true
/* ========================= */
var Singleton = (function () {
var instance;
return function Construct () {
if (instance) return instance;
if (this && this.constructor === Construct) {
instance = this;
} else {
return new Construct();
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment