Skip to content

Instantly share code, notes, and snippets.

@dmnsgn
Created April 16, 2016 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save dmnsgn/14d9f5d0c37870c83ba7e5d5b0653106 to your computer and use it in GitHub Desktop.
Save dmnsgn/14d9f5d0c37870c83ba7e5d5b0653106 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: constructor return an instance scoped to the module
// http://amanvirk.me/singleton-classes-in-es6/
let instance = null;
class SingletonModuleScopedInstance {
constructor() {
if (!instance) {
instance = this;
}
this._type = 'SingletonModuleScopedInstance';
this.time = new Date();
return instance;
}
singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
get type() {
return this._type;
}
set type(value) {
this._type = value;
}
}
export default SingletonModuleScopedInstance;
// ...
// index.js
import SingletonModuleScopedInstance from './SingletonModuleScopedInstance';
// Instantiate
const instance2 = new SingletonModuleScopedInstance();
console.log(instance2.type, instance2.singletonMethod());
// Time test
console.log(instance2.time);
// Getter/Setter
instance2.type = 'type updated';
console.log(instance2.type);
setTimeout(() => {
const instance2ReinstanciateAttempt = new SingletonModuleScopedInstance();
console.log(instance2ReinstanciateAttempt.time); // Return the same time
}, 1000);
// Static method
console.log(SingletonModuleScopedInstance.staticMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment