Created
August 17, 2014 17:14
-
-
Save adamgibbons/096d511da53e93180b10 to your computer and use it in GitHub Desktop.
Module Pattern in JavaScript
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
// 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