Access a copied integer variable in javascript anonymous method

安稳与你 提交于 2019-12-08 17:30:39

问题


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?


回答1:


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++;
}



回答2:


Curly braces ({}) in JavaScript do not capture variables as they do in C#.

Only closures (functions) introduce new scope, and capture variables.

var i = 0;
while (i < 2) {
  var contextCopy = i;
  ...
}

is actually interpreted as:

var i, contextCopy;
i = 0;
while (i < 2) {
  contextCopy = i;
  ...
}

To get a copy of the variable, you'll need to wrap the code with a closure:

var i;
i = 0;
while (i < 2) {
  (function (contextCopy) {
  ...
  }(i));
}



回答3:


You don't create a copy of the i variable. Instead, you make this variable GC-dependant of the closures that use it. It means that when the while loop exits, the i variable continues to live in its last state (1) and both closures reference to it.

Another way to put it: closing over a variable does not copy it into your closure (would make little sense for objects), it just makes your closure reference the variable and ensures this variable is not GCed untill the closure is.



来源:https://stackoverflow.com/questions/8214753/access-a-copied-integer-variable-in-javascript-anonymous-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!