Skip to content

Instantly share code, notes, and snippets.

@ondratra
Created August 20, 2016 22:06
Show Gist options
  • Save ondratra/2909328eb2c28c2674d3c3b6ccf5e4d2 to your computer and use it in GitHub Desktop.
Save ondratra/2909328eb2c28c2674d3c3b6ccf5e4d2 to your computer and use it in GitHub Desktop.
ECMA6 Singleton class
const constructorLock = Symbol();
const singletonInstance = Symbol();
export default class Singleton {
// constructor lock prevents class from being instantiate via 'new Singleton()'
// because constructorLock exists only in this file
constructor(lock) {
if (lock !== constructorLock) {
throw new Error('Cannot instantiate singleton directly. Use getter "instance".');
}
}
static get instance() {
if (!this[singletonInstance]) {
this[singletonInstance] = new Singleton(constructorLock);
}
return this[singletonInstance];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment