First Post: JS Closure Example

While creating 10 <a> elements, each link pointing at a different id number. In that case, this example makes sense.

for (var i = 0; i < 10; i++) {
    var a = document.getElementById('a');
    a.onclick = function(e) {
        location.href = 'http://www.example.com/?id=' + i;
    };
    document.body.appendChild(a);
}

However, the creation of the anonymous function block encloses a reference to the variable i but the value of i keeps changing as the for loop loops. That ends up yielding all 10 links linking to http://www.example.com/?id=10.

To correct that each anonymous function needs it’s own copy of i. To do that.

for (var i = 0; i < 10; i++) {
    var a = document.getElementById('a');
    a.onclick = (function(internal_i) {
        return function(e) {
            location.href = 'http://www.example.com/?id=' 
                          + internal_i + '&lastId=' + i;
        };
    })(i);
    document.body.appendChild(a);
}

Having the anonymous function block be returned by another anonymous function block that is passing the looping variable into it causes a new copy of i to be created.

Wrapping an anonymous function block in parenthesis allows you to follow it with a parameter list which will call the function immediately and thus return the function event handler with the closure. The event handler has references to both i and it’s outer function’s internal_i.

Enhanced by Zemanta