Closure sample

Explain closure

by Boban Stojanovski

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<div id="noClosure"><h3>No Closure</h3></div>    
<div id="Closure"><h3>Closure</h3></div>

JavaScript

for(var i = 0; i < 3 ;i++)
{ 
    var $btn = $("<button>", {
        class :"btn btn-primary" , 
        text : "Click Me "+ i ,
        click : function(){ alert(i); },
        style:"margin-right:10px"
    });
    
    $("#noClosure").append($btn);
}
 
for(var j = 0; j < 3 ;j++)
{ 
    var $btn = $("<button>", {
        class :"btn btn-success" , 
        text : "Click Me "+ j ,
        click : function(index){ 
            return function(){
                //The value of j is enclosed
                //with the value it has at the time
                // of creating of this function
                alert(index); 
            }
        }(j),
         style:"margin-right:10px"
    });

    $("#Closure").append($btn);
}