Skip to content

Instantly share code, notes, and snippets.

@QGao
Created January 20, 2012 23:11
Show Gist options
  • Save QGao/1650137 to your computer and use it in GitHub Desktop.
Save QGao/1650137 to your computer and use it in GitHub Desktop.
A n ice singleton patten sample from Rick
/**
* A singleton object
*
* Singleton objects are useful but use them sparingly. By using singletons
* you are creating dependencies in your software that might not be necessary.
* If you find yourself using this over and over again you probably need
* to rethink what you're doing. Remember, in general, globals are bad.
*/
var Preferences = {
fbToken: '1234',
twToken: '1234',
userData: {},
updateUser: function() {},
nukeProject: function() {}
};
/**
* Alternative way of creating a singleton
* using revealing module pattern
*/
var Preferences = (function() {
var fbToken = '1234',
twToken = '1234',
userData = {},
updateUser = function() {},
nukeProject = function() {};
return {
fbToken: fbToken,
twToken: twToken,
userData: userData,
updateUser: updateUser,
nukeProject: nukeProject
}
})();
/**
* Alternative way of creating a singleton
* using normal module pattern
*/
var Preferences = (function() {
var api = {};
api.fbToken = '1234';
api.twToken = '1234';
api.userData = {};
api.updateUser = function() {};
api.nukeProject = function() {};
return api;
})();
console.log( Preferences );
console.log( Preferences.fbToken );
console.log( Preferences.twToken );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment