Created
October 11, 2012 13:58
-
-
Save cgcardona/3872498 to your computer and use it in GitHub Desktop.
The 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
'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