在javascript for循环中使用匿名函数 [英] using anonymous function in javascript for loops

查看:135
本文介绍了在javascript for循环中使用匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了for循环中的匿名函数,在一两个地方引起新的范围,并想知道是否有意义。

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.

var attr, colors = ['green','blue','red'];

for ( attr = 0; attr < colors.length; attr++) {
    (function() {
        var colorAttr = colors[attr];

        // do something with colorAttr
    })();
}



我理解它与在for循环中保持作用域有关,但在什么情况下这是必要的?

I understand it has something to do with keeping the scope inside the for loop clean, but in what situations would this be necessary? Would it be good practice to do this everywhere you need to declare a new var inside the for loop?

推荐答案

如果你有内部的作为循环的一部分,函数不会立即执行。

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

即使 var color 在循环内,循环也没有作用域。你实际上只有一个变量,每个循环迭代使用。因此,当超时触发时,它们都使用相同的值,即循环设置的最后一个值。

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

这将捕获每次迭代到一个函数的参数中的值,它创建一个作用域。现在每个函数获取一个 color 变量的自己版本,当该循环中创建的函数稍后执行时,该变量不会改变。

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.

这篇关于在javascript for循环中使用匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆