JavaScript – Encapsulation

In JavaScript everything is an object from the obvious, such as arrays, strings etc. through to functions.

So how do we handle encapsulation such that we will have private and public data and methods ?

Well, because functions are themselves objects we can declare private data internally (within the function) and then using the prototype property we can add methods to the function that are public.

Below is a very simple example of encapsulation. The variable balance is private as it’s declared within the scope of the BankAccount function.

function BankAccount() {
   var balance = 0;

   BankAccount.prototype.add = function(amount) {
      balance += amount;
   }

   BankAccount.prototype.subtract = function(amount) {
      balance -= amount;
   }

   BankAccount.prototype.getBalance = function() {
      return balance;
   }
};

The functions add, subtract and getBalance are public and thus we can interact with this object using the following

var bankAccount = new BankAccount();
bankAccount.add(100);
bankAccount.subtract(10);

var current = bankAccount.getBalance();

If we wanted to make the balance variable public, we could simply alter the var balance = 0 to this.balance = 0 but of course this allows us to change the balance variable without going through the add/subtract methods.

To implement a more property like variable (as per C# for example) whereby we have methods to get/set the property we might look to implement something like

function BankAccount() {
   var balance = 0;

   this.__defineSetter__("balance", function(x) {});
   this.__defineGetter__("balance", function() { return balance; });
   
   // rest of the methods as before
};

Here we define a getter such that we can access in this way bankAccount.balance but we’ve defined a setter that does nothing so whilst a setter exists it doesn’t alter the balance.