在 javascript for 循环中使用匿名函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13977046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using anonymous function in javascript for loops
提问by Evan
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 循环中的匿名函数在一两个地方在网络上引入新的作用域,想知道它是否有意义。
for example:
例如:
var attr, colors = ['green','blue','red'];
for ( attr = 0; attr < colors.length; attr++) {
(function() {
var colorAttr = colors[attr];
// do something with colorAttr
})();
}
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?
我知道这与保持 for 循环内的范围清洁有关,但是在什么情况下这是必要的?在需要在 for 循环中声明新 var 的任何地方都这样做是否是一种好习惯?
回答by Alex Wayne
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 color
在循环内,循环也没有作用域。您实际上只有一个变量供每个循环迭代使用。因此,当超时触发时,它们都使用相同的值,即循环设置的最后一个值。
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.
这个函数在每次迭代时将值捕获到函数的参数中,这会创建一个作用域。现在每个函数都有自己的color
变量版本,当在该循环中创建的函数稍后执行时,该版本不会改变。
回答by jAndy
You're almost there. It makes only sense in your snippet, if you pass inthe attr
value into your self invoking functionas an argument. That way, it can store that variable within its very own scope object
你快到了。它使你的代码段只可意会,如果你在传递的attr
价值到您的自调用函数作为参数。这样,它就可以将该变量存储在它自己的作用域对象中
(function( attr ) {
var colorAttr = colors[attr];
// do something with colorAttr
})( attr );
Now, the activation objectrespectively lexical environment record(which are ES3 and ES5 scope objects) will have an entry for whatever value is behind attr
and therefore, its closured.
现在,激活对象分别是词法环境记录(它们是 ES3 和 ES5 范围对象)将有一个条目,用于后面的任何值attr
,因此,它的closured.