Created
August 25, 2016 18:46
-
-
Save vibhanshuc/3bcb43b3fff79cb6d50f1c4e94957724 to your computer and use it in GitHub Desktop.
Contains an example of a singleton
This file contains 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
// 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