Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #18935

Re: Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables

From Gregor Kofler <usenet@gregorkofler.com>
Newsgroups comp.lang.javascript
Subject Re: Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables
Date 2013-03-18 18:04 +0100
Organization A noiseless patient Spider
Message-ID <ki7hba$fp2$1@dont-email.me> (permalink)
References <3e54afae-ea56-43c0-95d8-e6a173d8c1a6@googlegroups.com>

Show all headers | View raw


Am 2013-03-18 13:29, schrieb pwellner@gmail.com:

> I have a mysterious problem in my JavaScript which is -- or seems to be -- in the nature of JavaScript itself, but I don't find the reason why and I don't have any idea of how to workaround this unless using eval() code.
>
> If I define a function within a loop with two variables (which should be different variables in my eyes, and their content is different in the time of defining this function), all functions I defined in the loop are using the exact same variable (and exact same content). I created a very simple example demonstrating this:
>
> var inputParams = ['x', 'y'];
> var funcs = [];
> for(var i = 0; i < 2; i++) {
>      var variableInLoop = inputParams[i];
>      var funcInLoop = function(){return 'prefix '+variableInLoop;};
>      funcs.push(funcInLoop);
> }
>
> After this code, funcs[0]() funcs[1]() will return the same result: 'prefix y'.

As expected. Once the loop finishes you have two function bodies with 
the same content:

return 'prefix ' + variableInLoop;

and variableInLoop holds the value 'y'. You want to look up the concept 
of closures

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures

and keep in mind that JS is function scoped, not block scoped.

Gregor

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables pwellner@gmail.com - 2013-03-18 05:29 -0700
  Re: Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2013-03-18 17:44 +0100
  Re: Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables Gregor Kofler <usenet@gregorkofler.com> - 2013-03-18 18:04 +0100
  Re: Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables Jim T. <x@y.z> - 2013-03-19 12:01 -0500
    Re: Defining two functions in a loop referring to variables scoped in the loop behave as their were global variables Jim T. <x@y.z> - 2013-03-19 12:25 -0500

csiph-web