Jump to navigation


"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

// Halifax Bank

// Returns remaining balance

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

// undefined

Summary of object member access - zipcon

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

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