Skip to content

Instantly share code, notes, and snippets.

@vibhanshuc
Created August 25, 2016 18:46
Show Gist options
  • Save vibhanshuc/3bcb43b3fff79cb6d50f1c4e94957724 to your computer and use it in GitHub Desktop.
Save vibhanshuc/3bcb43b3fff79cb6d50f1c4e94957724 to your computer and use it in GitHub Desktop.
Contains an example of a singleton
// Create a closure
var SecretStore = (function() {
var data, secret, newSecret;
// Emulation of a private variables and functions
data = 'secret';
secret = function() {
return data;
}
newSecret = function(newValue) {
data = newValue;
return secret();
}
// Return an object literal which is the only way to access the private data.
return {
getSecret: secret,
setSecret: newSecret,
};
})();
var secret = SecretStore;
// => "secret"
console.log(secret.getSecret());
// => "foo"
console.log(secret.setSecret("foo"));
// => "foo"
console.log(secret.getSecret());
var secret2 = SecretStore;
// => "foo"
console.log(secret2.getSecret());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment