Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript closure work in this case?

How does JavaScript closure work in this case and to be more specific: what does the (i) at the end do?

for(var i = 0; i < 10; i++) {
    (function(e) {
        setTimeout(function() {
            console.log(e);  
        }, 1000);
    })(i);
}

Also I'm trying to implement it in my code, and it seems I don't get it right

for (var i=0; i < len; i++) {

    var formID = document.forms["form-" + i];
    $(formID).bind("submit", validate);

    $(formID).bind("change", function(i){
        var divI = '#ind-' + i;
        $(divI).css("background-color","green");
    })(i);
}
like image 844
ilyo Avatar asked Dec 07 '22 21:12

ilyo


1 Answers

This is a pattern used to create local scope around a variable. If this wasn't used then every call to console.log(i) would log the value of i (10) after the for loop finished.

for(var i = 0; i < 10; i++) {
    // create new function
    (function(e) {
        // log each counter after 1 second.
        setTimeout(function() {
            console.log(e);  
        }, 1000);
    // execute it with the counter
    })(i); 
}

The above is the same as this.

function foobar(e) {
    setTimeout(function() {
         console.log(e);
    }, 1000);
}

for (var i = 0; i < 10; i++) {
    (
        foobar
    )(i);
}

The real problem here is creating functions in a loop. don't do it :)

Your code

for (var i=0; i < len; i++) {

    var formID = document.forms["form-" + i];
    $(formID).bind("submit", validate);
    // create a full closure around the block of code
    (function() {
        $(formID).bind("change", function(i){
            var divI = '#ind-' + i;
            $(divI).css("background-color","green");
        })//(i); Don't call (i) here because your just trying to execute the 
        // jQuery element as a function. You can't do this, you need to wrap 
        // an entire function around it.
    })(i);
}

But that is wrong, you want to delegate this job to something else.

function makeGreen(form, i) {
    $(form).change(function() {
         $("#ind-"+i).css("background-color", "green");
    });
}

for (var i=0; i < len; i++) {
    var formID = document.forms["form-" + i];
    $(formID).bind("submit", validate);
    // call a helper function which binds the change handler to the correct i
    makeGreen(formID, i);
}

If you want to get a bit clever you can get rid of these anonymous functions

function makeGreen() {
     var divId = $(this).data("div-id");
     $(divId).css("background-color", "green");
}

for (var i=0; i < len; i++) {
    $(document.forms["form-" + i])
        .bind("submit", validate)
        // store i on the form element
        .data("div-id", "#ind-" + i)
        // use a single event handler that gets the divId out of the form.
        .change(makeGreen);
}

Edit

( // contain the function we create.
    function(parameterA) {
         window.alert(parameterA);
    }
) // this now points to a function
("alertMessage"); // call it as a function.

Is the same as

( // contain the window.alert function
    window.alert
) // it now points to a function
("alertMessage"); // call it as a function
like image 109
Raynos Avatar answered Dec 27 '22 04:12

Raynos