1

I'm working with a dynamically created function in a loop.

for (var i = 0; i < 4; i++) {
        window["functiontest" + i] = function () { alert(i); }
}

It works, but not how I want to get it working. Because when I do this, it means when the functiontest0 will run it will alert "3" because it actually alerts var i while the loop has finished adding to i.

What I want is to somehow "hardcode" the current i so it will actually alert "0" and not "3". I mean something like this:

window["functiontest" + i] = function () {
  // I need just the current state for `i` here and
  // not just the variable `i` - so for exampe I need
  // it as `i` literally put 0
}

Is there any way I can force it to write the result into a "string" or something else?

THX for help guys. and sorry for duplicate couldnt find anything while searching for it. mostly because i couldnt explain it that well :-)

but i ended up with something like this:

 for (var genfunc = 0; genfunc < 4; genfunc++) {

   if (genfunc == 0) { //left
       window["keyDown" + sys_curcontrols[genfunc]] = (function (unique) {
           return function () { window["sys_keyLeft" + unique] = -1; }
       })(nid);
   }
JohnMalkowich
  • 298
  • 3
  • 14

2 Answers2

2

A perfect example of where you need to use a function to create scope.

for (var i = 0; i < 4; i++) {
    window["functiontest" + i] = (function(index) {
        return function () { alert(index); }
    })(i);
}
Lukas
  • 9,765
  • 2
  • 37
  • 45
  • No. It's a perfect example of when to execute a function to create scope. If we define a closure as being a function with free variables, then the function you just added is not a closure. The function you return however (and the function the original code) are closures, and that's why the problem even exists (and because of how JavaScript deals with free variables). – Felix Kling Feb 21 '13 at 21:12
  • 1
    @FelixKling, good point. I've modified the answer. – Lukas Feb 21 '13 at 21:19
2

You're passing the variable by reference. Shadow the variable with an anonymous function to pass the value:

(function(i) {
    window['functiontest' + i] = function() {
        alert(i);
    };
})(i);

Also, don't make globals like this. Use an object:

var functiontest = {};

(function(i) {
    functiontest[i] = function() {
        alert(i);
    };
})(i);
Blender
  • 289,723
  • 53
  • 439
  • 496
  • thx for help... but why isnt it good to use globals? i need to be able to get the functions everywhere... is it a performance issue? – JohnMalkowich Feb 21 '13 at 21:34
  • 1
    @JohnMalkowich: No, it's just not maintainable. It's not the globals that are the problem here. It's that you're making a *lot* of global variables that should be contained in an object. – Blender Feb 21 '13 at 23:37