How to create closure in loop and store it in variable for later execution

≡放荡痞女 提交于 2019-12-24 00:52:50

问题


See code below. I've tried to strip it to its bare bones.

I have a _queue array. I want to iterate 10 times. On each iteration, I want to create a function that has a properly scoped reference for j (i.e. j=0 on the first iteration, j=1 on the second iteration, etc.)

I want to store that function in variable f, and then add f to the _queue array so I can call it later.

The problem of course is that on each iteration of the first loop, instead of storing the closure in f, it immediately executes the closure.

My question is this: How do I store the function with its proper j variable so that I can add it to the _queue array?

    _queue = [];

    for (j = 0; j < 10; j++) {

        var f =
          (function (index) {
            alert(index);
        })(j);                    //code is executed here instead of stored in the f variable

        _queue.push(f);  //Add f 

    }

    for (k = 0; k < _queue.length; k++){
        _queue[k].call();
    }

回答1:


Using an immediate function (or in general using a function) to introduce a new scope is correct. But you have to return a function from the immediate function:

var f = (function (index) {
    return function() {
       alert(index);
    };
}(j));     


来源:https://stackoverflow.com/questions/5606059/how-to-create-closure-in-loop-and-store-it-in-variable-for-later-execution

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