Closure Example

Demonstrating the need of closure

by jiggle

HTML

<p style="background-color:khaki">If you want to preserve the variable i value for each loop so that when the button will be clicked it will show their own value then this can not be done without closure principle.<p> 
<div id="buttonList"><h1>Without Closure</h1></div>


<div id="buttonListc"><h1>With Closure it is now corrected.</h1></div>

JavaScript

/*
*Below sample for having 10 buttons with its own values
*What would be the out put if you click on each button ?
*/
//*
var button , buttonList = document.getElementById("buttonList"),br;
for(var i = 0; i<10 ; i++) {
    
    br=document.createElement("br");
    buttonList.appendChild(br);
    button = document.createElement("input");
    button.onclick = function( ) {
        alert(iVal);
    } 
   
    button.type="button";
    button.value="Click " + i;
    buttonList.appendChild(button);
       
}



//*/

/*
*Solving above issue using closure principle.
*/
var button , buttonList = document.getElementById("buttonListc"),br,fnclosure;
for(var i = 0; i<10 ; i++) {
    
    fnclosure = function(p){
        br=document.createElement("br");
        buttonList.appendChild(br);
        button = document.createElement("input");
        button.onclick = function( ) {
            alert(p);
        } 
       
        button.type="button";
        button.value="Click " + i;
        button.style.backgroundColor="khaki";
        buttonList.appendChild(button);
               
    }
    fnclosure(i);
}