I am a C# developer and used to the way closures work in C#. Currently I have to work with anonymous javascript functions and experience a problem with the following snippet:
    function ClosureTest() {
    var funcArray = new Array();
    var i = 0;
    while (i < 2) {
        var contextCopy = i;
        funcArray[i] = function() { alert(contextCopy); return false; };
        i++;
    }
    funcArray[0]();
    funcArray[1]();
}
I expect the first funcArray() call to say 0 and the second to say 1. However, they both say 1. How is that possible?
By writing var contextCopy = i I make sure that I create a copy of the i-variable. Then, in each while-iteration I create a completely new function pointer. Each function refers to its own copy of i, which is contextCopy. However, both created functions for some reason refer to the same contextCopy-variable.
How does this work in javascript?
JavaScript has lexical closures, not block closures. Even though you are assigning i to contextCopy, contextCopy is, itself, a lexical member of ClosureTest (which is different from C#, where the {} give you a new scoped block). Try this:
while (i < 2) {
    funcArray[i] = (function(value) { 
        return function(){ alert(value); return false; }
    })(i);
    i++;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With