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);
   }
4

2 に答える 2

2

関数を使用してスコープを作成する必要がある場所の完璧な例です。

for (var i = 0; i < 4; i++) {
    window["functiontest" + i] = (function(index) {
        return function () { alert(index); }
    })(i);
}
于 2013-02-21T21:10:30.250 に答える
2

変数を参照渡ししています。匿名関数で変数をシャドウして、値を渡します。

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

また、このようなグローバルを作成しないでください。オブジェクトを使用します。

var functiontest = {};

(function(i) {
    functiontest[i] = function() {
        alert(i);
    };
})(i);
于 2013-02-21T21:11:01.360 に答える