Created
November 16, 2016 13:33
-
-
Save JavaTheNutt/0d9acc845d7f879cecb2fc1c7fbed5d2 to your computer and use it in GitHub Desktop.
This is an example of how to use closures for a module pattern in JavaScript
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
/** | |
*This function can be thought of as a 'class' to be instantiated | |
* | |
*/ | |
function User(){ | |
//private members | |
var username; | |
var password; | |
//constructor | |
function doLogin(user, pass){ | |
username = user; | |
password = pass; | |
} | |
//accessor for username | |
function retrieveUsername(){ | |
return username; | |
} | |
//publicly exposed functions | |
var publicApi = { | |
login: doLogin, | |
getUsername: retrieveUsername | |
} | |
return publicApi; | |
} | |
var joe = User(); | |
joe.login('IAmJoe', 'MeMeMe'); | |
var username = joe.getUsername(); | |
var chelle = User(); | |
chelle.login('chelle', 'iamchelle'); | |
var username = joe.getUsername(); | |
var user2 = chelle.getUsername(); | |
console.log(username); //logs 'IAmJoe' | |
console.log(user2); //logs 'chelle' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment