Skip to content

Instantly share code, notes, and snippets.

@adamgibbons
Created August 17, 2014 17:14
Show Gist options
  • Save adamgibbons/096d511da53e93180b10 to your computer and use it in GitHub Desktop.
Save adamgibbons/096d511da53e93180b10 to your computer and use it in GitHub Desktop.
Module Pattern in JavaScript
// Module Pattern in JS
var FriendsModule = (function(){
// private vars and functions
var friends = ['Adam', 'Brittany', 'Russell', 'Erik', 'Hank'];
var addFriend = function(friend) {
friends.push(friend);
};
var listFriends = function() {
var list = [];
friends.forEach(function(friend, idx) {
list.push(idx + 1 + ') ' + friend);
});
return list.join('\r\n');
};
var removeFriend = function(name) {
friends.forEach(function(friend, idx) {
if (name == friend)
friends.splice(idx, 1);
});
};
// public vars and aliases to private functions
return {
add: function(friend) {
addFriend(friend);
},
count: function() {
console.log(friends.length);
},
list: function() {
console.log(listFriends());
},
remove: function(name) {
removeFriend(name);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment