Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

Everyone's favourite Closure

Prerequisites:

  • Basics - JavaScript Objects,
  • JavaScript closure

Advantage of Using JavaScript Closures:

In the previous posts, the discussion was about how a closure is defined. That was the boring theory part and let's put that out of our way in this post. A small overview of the boring theory - A closure allows the association of some data with a function that operates on that data. NOT CLEAR enough? This is similar to the definition of an Object Oriented Programming Language, where an Object allows association of some data with one or more methods.

Most of the JavaScript code that we write are based on Evented Handling of Functions and Objects. The browser captures several events performed on the DOM, and we attach event handlers as a callback(a single function that is executed as a response) to those events, prevent default actions, perform user defined actions, write code overriding the default configurations and native programs, etc.…

Let's start with an example.

    function changeColor(colorCode) {
         return function() {
             document.body.style.backgroundColor = colorCode;
         };
    }

and is implemented in the following way

    function createButtonActions() {
       var $ = function(eid) {
         return document.getElementById(eid);
       }
       $("button_blue").onclick = changeColor("blue");
       $("button_fav").onclick = changeColor("#abcdef");
    }

Private Members in JavaScript:

This is one of the major advantages of JavaScript Closures. Java allows one to define a private member and can restrict access to that private member. But JavaScript natively doesn't support that feature. But it does provide an efficient way of restricting access to code, managing the global namespace, and abstracting non-essential methods from public interface to the code.

As defined by the tradition, an example.

    var Counter = (function() {
      var privateCounter = 0;
      function changeBy(val) {
        privateCounter+=val;
      }
      return {
        increment: function() {
         changeBy(1);
       },
        decrement: function() {
          changeBy(-1);
        },
        value: function() {
          return privateCounter;
        }
      }
    })();

Now there is nothing much to explain what this does. But there are many hidden facts that are of importance. Lets go point by point.

  • This is an example of the FAVORITE CLOSURE that the topic says.
  • In previous example, the closure had its own environment. But here, we have a single environment shared by three different functions.

    • Counter.increment
    • Counter.decrement
    • Counter.value
  • The private items are

    • a variable : privateCounter
    • a function : changeBy
  • The most important thing - The pattern of definition of "Counter".

    • Counter = ( function ( ) { } ) ( ) ;
    • This is called a self-executing anonymous function and is the FAVORITE CLOSURE used by all JavaScript Enthusiasts.

Favourite Closure:

As said in the previous paragraph, the anonymous function (in analogy by its name [=NULL]) that is self executing is the favourite Closure pattern.

( function ( myParam ) { } ( "parameter" ) ;

here we are just bypassing a variable declaration at the top.

    ( function ( window, document, undefined ) {
        // ...
    } ) ( this, this.document );

is the MOST FAVORITE CLOSURE PATTERN. Now why is this the favourite closure? The answer to that would be simple enough to guess.

  • It is self executing.
  • here ‘this’ is always the global object when in global scope. So we can safely use it.

When minified,

    (function(w,d,u){})(this, this.document);

This speeds up the traversal a little bit and is protective in places where someone does undefined = true.