Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kccheung/bcc84d1a7a76f5f3ab026d2117c48801 to your computer and use it in GitHub Desktop.
Save kccheung/bcc84d1a7a76f5f3ab026d2117c48801 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: module default exports an instance
class SingletonDefaultExportInstance {
constructor() {
this._type = 'SingletonDefaultExportInstance';
}
singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
get type() {
return this._type;
}
set type(value) {
this._type = value;
}
}
export default new SingletonDefaultExportInstance();
// ...
// index.js
import SingletonDefaultExportInstance from './SingletonDefaultExportInstance';
// Instantiate
// console.log(new SingletonDefaultExportInstance); // is not a constructor
// Prototype Method
console.log(SingletonDefaultExportInstance.type, SingletonDefaultExportInstance.singletonMethod());
// Getter/Setter
SingletonDefaultExportInstance.type = 'type updated';
console.log(SingletonDefaultExportInstance.type);
// Static method
console.log(SingletonDefaultExportInstance.constructor.staticMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment