Last active
May 5, 2017 11:55
-
-
Save YozhEzhi/0d9c1c1770b06a84a87656f91d8ce8d8 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 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