Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a copied integer variable in javascript anonymous method

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?

like image 440
TwinHabit Avatar asked Nov 21 '11 16:11

TwinHabit


1 Answers

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++;
}
like image 69
Matt Avatar answered Oct 02 '22 13:10

Matt