“Encapsulation is the art of including everything that’s needed inside a object to ensure it can operate properly, and also that nothing can interfere from the outside”

Example of data being encapsulated, the balance cannot be accessed or altered in anything other than the withdraw function where it was returned.

function BankUser(balance, bankName) {
  var balance = balance;
  this.bankName = bankName;
  this.withdraw = function(amount) {
    return balance - amount;
  }
}

var shane = new BankUser(1000000, 'Halifax Bank');

// Undefined
console.log(shane.balance);

// Halifax Bank
console.log(shane.bankName);

// Returns remaining balance
console.log(shane.withdraw(999999));

Self invoking anonymous function expression
JavaScript variables have either function scope, or global scope. There is no block scope. Enclosing your code in a self invoking function like the one in your example (see below) creates a temporary local scope for single-use, immediately-run code, without polluting the global namespace. (Stackoverflow user Daniel Vassallo).

A common place for these to be found would be a JS plugin, as they don’t want to interfere with – or be interfered by – any code that was written by the user.

// A self invoking anonymous function expression
(function() {
  var myName = 'shane';
  // returns Shane
  console.log(myName);
})();

// undefined
console.log(myName);

Summary of object member access – zipcon

Private
members can only be accessed within constructor and public method code, using this keyword.
methods can access private members, but not public ones

Public
members can be accessed anywhere using the dot notation
methods can access both public and private members

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.

View