using anonymous function in javascript for loops

后端 未结 2 1115
孤街浪徒
孤街浪徒 2020-12-13 14:57

I have seen anonymous functions inside for loops to induce new scope on the web in one or two places and would like to know if it makes sense.

for example:



        
相关标签:
2条回答
  • 2020-12-13 15:41

    You're almost there. It makes only sense in your snippet, if you pass in the attr value into your self invoking function as an argument. That way, it can store that variable within its very own scope object

    (function( attr ) {
        var colorAttr = colors[attr];
    
        // do something with colorAttr
    })( attr );
    

    Now, the activation object respectively lexical environment record (which are ES3 and ES5 scope objects) will have an entry for whatever value is behind attr and therefore, its closured.

    0 讨论(0)
  • 2020-12-13 15:47

    When you have inner functions that are not executed immediately, as part of the loop.

    var i, colors = ['green', 'blue', 'red'];
    
    for (i = 0; i < colors.length; i++) {
        var color = colors[i];
        setTimeout(function() {
            alert(color);
        }, i * 1000);
    }
    
    // red
    // red
    // red
    

    Even though var color is inside the loop, loops have no scope. You actually only have one variable that every loop iteration uses. So when the timeouts fire, they all use the same value, the last value set by the loop.

    var i, colors = ['green', 'blue', 'red'];
    
    for (i = 0; i < colors.length; i++) {
        (function(color) {
            setTimeout(function() {
                alert(color);
            }, i * 1000);
        })(colors[i]);
    }
    
    // green
    // blue
    // red
    

    This one captures the value at each iteration into an argument to a function, which does create a scope. Now each function gets it's own version of a color variable which won't change when functions created within that loop are later executed.

    0 讨论(0)
提交回复
热议问题