Last active
April 16, 2016 17:35
-
-
Save dmnsgn/5e932985323596343bb660308869d9a7 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: using objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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