了解JavaScript / Node中的闭包引起的变量捕获 [英] Understanding variable capture by closures in Javascript/Node
问题描述
除了标准之外,JavaScript中的变量捕获有一个确定的来源(这是阅读标准的痛苦吗?)
在下面的代码 i <0; i <10;
{
(function(i)
{
process.nextTick(function()
{
console.log(i)
})
})(i)
}
..10。 process.nextTick
是节点中 setTimeout(f,0)
的模拟。
但是在下一个代码中,我似乎不被复制:
for(var i = 0; i <10; i ++)
{
var j = i
process.nextTick(function()
{
console.log(j)
})
}
它打印9次10次。为什么?我对参考/一般文章比解释这个具体的捕获案例更感兴趣。
一个方便的参考。但底线是:在第一个,你显式地传递 i
到一个匿名函数,它创建一个新的范围。您不是在第二个中为 i
或 j
创建新作用域。此外,JavaScript总是捕获变量,而不是值。
JavaScript var
关键字具有函数范围,而不是块范围。因此,for循环不会创建作用域。
注意,非标准的 let
关键字具有本地作用域。
Is there a definite source on variable capture in Javascript besides the standard (it's a pain to read the standard)?
In the following code i
is copied by value:
for (var i = 0; i < 10; i++)
{
(function (i)
{
process.nextTick(function ()
{
console.log(i)
})
}) (i)
}
So it prints 1..10. process.nextTick
is an analog of setTimeout(f,0)
in node.
But in the next code i doesn't seem to be copied:
for (var i = 0; i < 10; i++)
{
var j = i
process.nextTick(function ()
{
console.log(j)
})
}
It prints 9 10 times. Why? I'm more interested in a reference/general article than in explaining this concrete case of capture.
I don't have a handy reference. But the bottom line is: In the first, you're explicitly passing in i
to an anonymous function, which creates a new scope. You are not creating a new scope for either i
or j
in the second. Also, JavaScript always captures variables, not values. So you would be able to modify i too.
The JavaScript var
keyword has function scope, not block scope. So a for loop does not create a scope.
As a note, the non-standard let
keyword has local scope.
这篇关于了解JavaScript / Node中的闭包引起的变量捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!