Last active
September 25, 2017 07:24
-
-
Save jlyu/467ab5a79128e7d2fa65d3ed950580ae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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