Closures in loops

by sramnan

HTML

<div class="buttonCollection" id="nonClosure">
    <h1>Example using private variable in a loop:</h1>
    <button>Hello</button>
    <button>this</button>
    <button>is</button>
    <button>a</button>
    <button>button</button>
    <button>collection</button>
</div>
<div class="buttonCollection" id="closure">
    <h1>Example using closure:</h1>
    <button>Hello</button>
    <button>this</button>
    <button>is</button>
    <button>a</button>
    <button>button</button>
    <button>collection</button>
</div>

CSS

div.buttonCollection {
    border: 5px solid #9ac;
    background: #abe;
    margin: 32px;
}

JavaScript

nonClosureMethod();
closureMethod();

function nonClosureMethod() {
    var buttons = document.getElementById("nonClosure")
        .getElementsByTagName("button");
    for(var i = 0; i < buttons.length; i++) {
        var thisButton = buttons[i];
        var buttonText = thisButton.innerText;
        thisButton.addEventListener("click", function(e) {
            alert(buttonText);
        });
    }
};

function closureMethod() {
    var buttons = document.getElementById("closure")
        .getElementsByTagName("button");
    for(var i = 0; i < buttons.length; i++) {
        var thisButton = buttons[i];
        var buttonText = thisButton.innerText;
        (function(c_buttonText) {
            thisButton.addEventListener("click", function() {
                alert(c_buttonText);
            });
        })(buttonText);
    }
};
function test(){
var x = "new";
console.log(x);

function innertest(){
console.log(x);
}
return innertest();
}
test();