Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Created October 11, 2012 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgcardona/3872498 to your computer and use it in GitHub Desktop.
Save cgcardona/3872498 to your computer and use it in GitHub Desktop.
The Module Pattern in Javascript
'use strict';
var balanceModule = (function(){
// Private variable
var balance = 0;
// Private functions
function logStatus(updateFigure, currentBalance, operatorSymbol, newBalanceFigure){
console.log(currentBalance + ' ' + operatorSymbol + ' ' + updateFigure + ' = ' + newBalanceFigure);
}
function updateBalance(updateFigure, operatorSymbol){
var newBalanceFigure;
if(operatorSymbol == '+')
newBalanceFigure = balance + updateFigure;
else if(operatorSymbol == '-')
newBalanceFigure = balance - updateFigure;
logStatus(updateFigure, balance, operatorSymbol, newBalanceFigure);
balance = newBalanceFigure;
}
return {
// Public functions
createBalance: function(initialBalanceAmount){
updateBalance(initialBalanceAmount, '+');
},
getBalance: function(){
return balance;
},
increaseBalance: function(amount){
updateBalance(amount, '+');
},
decreaseBalance: function(amount){
updateBalance(amount, '-');
},
deleteBalance: function(){
updateBalance(balance, '-');
}
};
})();
balanceModule.createBalance(100000);
console.log('new account balance: ' + balanceModule.getBalance());
balanceModule.increaseBalance(500000);
console.log('increase account balance: ' + balanceModule.getBalance());
balanceModule.decreaseBalance(200000);
console.log('decrease account balance: ' + balanceModule.getBalance());
balanceModule.deleteBalance();
console.log('delete account balance: ' + balanceModule.getBalance());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment