Skip to content

Instantly share code, notes, and snippets.

@jlyu
Last active September 25, 2017 07:24
Show Gist options
  • Save jlyu/467ab5a79128e7d2fa65d3ed950580ae to your computer and use it in GitHub Desktop.
Save jlyu/467ab5a79128e7d2fa65d3ed950580ae to your computer and use it in GitHub Desktop.
var Singleton = (function(){
var _instance;
function init() {
function privateMethod() {}
var privateVariable = "42";
var privateRandomX = Math.random();
return {
publicMethod: function() {},
publicProperty: "23",
getRandomX: function() { return privateRandomX; }
};
};
return {
getInstance: function() {
if (!_instance) {
instance = init();
}
return _instance;
}
};
})();
// version 2
// static property
function Singleton() {
if (typeof Singleton.instance === "object") {
return Singleton.instance;
}
// init here
Singleton.instance = this; // flaw: anyone can modify
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment