Skip to content

Instantly share code, notes, and snippets.

@dmnsgn
Last active April 16, 2016 17:35
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 dmnsgn/5e932985323596343bb660308869d9a7 to your computer and use it in GitHub Desktop.
Save dmnsgn/5e932985323596343bb660308869d9a7 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: using objects
// http://www.2ality.com/2011/04/singleton-pattern-in-javascript-not.html
const NoClassSingleton = {
_instance: null,
get instance() {
if (!this._instance) {
this._instance = {
singletonMethod() {
return 'singletonMethod';
},
_type: 'NoClassSingleton',
get type() {
return this._type;
},
set type(value) {
this._type = value;
}
};
}
return this._instance;
}
};
export default NoClassSingleton;
// Flux store way
export const NoClassSingletonObjectAssign = Object.assign({}, {
singletonMethod() {
return 'singletonMethod';
},
_type: 'NoClassSingletonObjectAssign',
get type() {
return this._type;
},
set type(value) {
this._type = value;
}
});
// ...
// index.js
import NoClassSingleton, { NoClassSingletonObjectAssign } from './NoClassSingleton';
// Instance
const instance = NoClassSingleton.instance;
// Prototype Method
console.log(instance.type, instance.singletonMethod());
// Getter/Setter
instance.type = 'type updated';
console.log(instance.type);
/*
Flux
*/
// Prototype Method
console.log(NoClassSingletonObjectAssign.type, NoClassSingletonObjectAssign.singletonMethod());
// Getter/Setter
NoClassSingletonObjectAssign.type = 'type updated';
console.log(NoClassSingletonObjectAssign.type);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment