Interview JavaScript private methods with closures for multiple objects exercise (not Module Singleton pattern!)

JavaScript private methods with closures

var accountObj = function() {
     var privateBalance = 0;
     function privateDeposit(val) { privateBalance += val; }
     return {
          deposit: function(n) { privateDeposit(n); },
          balance: function() { return privateBalance; }
     }
};

var myAccount = accountObj();
var yourAccount = accountObj();

myAccount.deposit(10);
console.log('My account balance: ' + myAccount.balance()); //10

yourAccount.deposit(200);
console.log('Your account balance: ' + yourAccount.balance()); //200

myAccount.deposit(5);
console.log('Added 5, balance updated: ' + myAccount.balance()); //15

console.log(myAccount.privateBalance); // undefined

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Another example:


var animal = function (spec) {
     var privateName = spec.name;
     var privateSaying = spec.saying;
     var privateReturnName = function(){
          return privateName;
     };
     var privateReturnSaying = function(){
          return privateSaying;
     }
     return {
          get_name: function(){
               return privateReturnName();
          },
          get_saying: function(){
               return privateReturnSaying();
          }
     }
};
var myHorse = animal({name: 'Wilbur', saying: 'Neeeeeeh'});
var myPig = animal({name: 'Charlotte', saying: 'Oink!'});
document.writeln(myHorse.get_name() + ' says ' + myHorse.get_saying()); <span style="color: #ff0000;">// Wilbur says Neeeeeeeh
document.writeln(myPig.get_name() + ' says ' + myPig.get_saying());

document.writeln(myPig.privateSaying); // undefined

Leave a Reply

You must be logged in to post a comment.