Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save YozhEzhi/85d1db271b37fab15098aa75c8dc0740 to your computer and use it in GitHub Desktop.
Save YozhEzhi/85d1db271b37fab15098aa75c8dc0740 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: constructor returns an instance scoped to the module. With using the `new` operator.
let instance;
class Singleton {
constructor() {
if (!instance) {
instance = this;
}
this._type = 'Singleton';
return instance;
}
singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
get type() {
return this._type;
}
set type(value) {
this._type = value;
}
}
export default Singleton;
// index.js
import Singleton from './Singleton';
// Instantiate
const instance2 = new Singleton();
console.log(instance2.type, instance2.singletonMethod());
// Getter/Setter
instance2.type = 'type updated';
console.log(instance2.type);
// Static method
console.log(Singleton.staticMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment