Last Updated: February 25, 2016
·
438
· jnuserful

javascript basic programming - the closures

The closures in javascript

In javascript we can use closures to access Private Variable within a function wrapper, using a anonymous nested function.

var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  alert('inside foo, call to f(): ' + f()); // "2"
}
foo();
alert("call to g(): " + g()); // "1"
alert("call to f(): " + f()); // "2"

Closures and Scope

It is important to note that when making a closure, it takes the last value of the variable of the wrapper function. A common case is when we use a loop.

window.onload = function(){  
    var el = document.getElementById("anyElement");  
    var events = [ "click", "mouseover", "mouseout" ];  

    for(var i=0;i<events.length;i++){  
        var item = events[i];  
        el[ "on" + item ] = function(){  
            alert( "event: " + item );  
        }  
    }  
}  

Note that the assignment of el["on" + item]" is a closure. The run this example notice that in each event onclick, onmouseover and onmouseout call the closure and mouseout always alert, the last value in the loop takes the variable item.

We can solve this by creating a new scope by a anonymous function that auto run. so in each execution of this function, item takes new values ​​and function take the last value contained in the wrapper function in each iteration is different.

That can be especially useful considering that javascript does not support to OOP, rather than that we can create pseudoclass using this feature.