Closure (JS the good parts)

Before talking about closure, let's start with scope first. Scope is a programming language controls the visibility and lifetimes of variables and parameters. Most languages have block scope, which means that a block of statements wrapped with curly braces are not visible from outside of the block.

However JavaScript does not have block scope even though its block syntax suggests that it does. JavaScript does have function scope. It means that a variable defined within a function is visible everywhere within the function. The closure feature is derived from function scope service. It enjoys the privilege of access to the outer value variable.

Typically, closure can be used to give each handler a unique number.

    var add_the_handlers = function(nodes){
        var i;
        for(i = 0; i < nodes.length; i += 1){
            nodes[i].onclick = function(i){
                return function(e){
                    alert(e);
                };
            }(i);
        }
    };

In this snippet, it defines a function and immediately invoke it, passing in i. That function will return an event handler function that is bound to the value of i that was passed in.

<<<<<<< HEAD It is worth noticing that in JavaScript, the inner function can have a longer lifetime than its outer function. ======= It is worth noticing that in JavaScript, the inner function can have a longer lifetim than its outer funciton.

origin/master

Instead of initializing myObject with an object literal, we will initialize myObject by calling a function that returns an object literal.

    var myObject = function(){
        var value = 0;
        return {
            increment: function(inc){
                value += typeof inc === 'number' ? inc : 1;
                },
            getValue: function(){
                return value;
                }
            };
        }();

We are not assigning a function to myObject. We are assigning the result of invoking that function. Notice the () on the last line. The function returns an object containing two methods, and those methods continue to enjoy the privilege of access to the value variable.