Created
February 18, 2015 10:52
-
-
Save you-think-you-are-special/e4a89de3ae347b1d4d76 to your computer and use it in GitHub Desktop.
ES6 Singleton example. Use: import Singleton from 'Singleton'; let instance = Singleton.instance;
This file contains 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
'use strict'; | |
/** | |
* Created by Alexander Litvinov | |
* Email: [email protected] | |
* May be freely distributed under the MIT license | |
*/ | |
let singleton = Symbol(); | |
let singletonEnforcer = Symbol(); | |
class Singleton { | |
/** | |
* @param enforcer | |
*/ | |
constructor(enforcer) { | |
if (enforcer !== singletonEnforcer) { | |
throw "Cannot construct singleton" | |
} | |
} | |
/** | |
* @returns Singleton | |
*/ | |
static get instance() { | |
if (!this[singleton]) { | |
this[singleton] = new Singleton(singletonEnforcer); | |
} | |
return this[singleton]; | |
} | |
} | |
export default Singleton; |
If I understand CommonJS + the browser implementations correctly, the output of a module is cached, so export default new MyClass()
will result in something that behaves as a singleton (only a single instance of this class will ever exist per process/client depending on env it's running in).
@StevenLangbroek export default new MyClass()
pattern is using in ReactJS dispacher which is a single component for a ReactJS app. I think, you are correct about it.
Refer: https://gist.github.com/milankarunarathne/c565aa5970987aeca88b
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@schankam, I'll have to check Babel out. I tried using some other ES6 transpiler once; I don't remember what it was called, but it didn't work out so well.