Interview JavaScript Module Pattern Singleton

var accountObj = (function() {
     var balance = 0;
     var type = 'savings';
     return {
          get_balance: function(){
               return balance;
          },
          deposit: function(a){
               balance += a;
          },
     };
}());

var myAccount = accountObj;
document.writeln('Balance: ' + myAccount.get_balance()); // 0
document.writeln('Add 5: ' + myAccount.deposit(5)); // undefined
document.writeln('Balance: ' + myAccount.get_balance()); // 5

Leave a Reply

You must be logged in to post a comment.