Encapsulation in JavaScript

In JavaScript, encapsulation is achieved by a a self invoking anonymous function expression.

JavaScript variables have either function scope, or global scope. There is no block scope. Enclosing our code in a self invoking function like the one in our example creates a temporary local scope for single-use, immediately-run code, without polluting the global namespace.

(function() { 
   var x = '';
   function myFunction () {
      alert('Hello: ' + x);
   }
   x = 'Bob';
   myFunction();
   alert(typeof x);          // string
   alert(typeof myFunction); // function
})();

alert(typeof x);           // undefined
alert(typeof myFunction);  // undefined

Whatever we declare the self invoking function is held in a separate scope. The variable x and the function myFunction() cannot be accessed from anywhere else and it would be free to declare another function myFunction() without conflicts.

results matching ""

    No results matching ""