Skip to content

Instantly share code, notes, and snippets.

@JavaTheNutt
Created November 16, 2016 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavaTheNutt/0d9acc845d7f879cecb2fc1c7fbed5d2 to your computer and use it in GitHub Desktop.
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 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