[英]Confused about function closures
Can someone please explain why does it console log out 10, 10, 10 instead of 9, 9, 9? 有人可以解释一下为什么控制台注销10、10、10而不是9、9、9吗? When it goes through for loop shouldn't it stop at 9?
当它通过for循环时,它不应该停在9吗?
var foo = [];
for (var i = 0; i < 10; i++) {
foo[i] = function() {
return i;
};
};
console.log(foo[0]());
console.log(foo[1]());
console.log(foo[2]());
Whenever any function
which is using any variable from parent scope is executed, it gets that value of a variable which it is holding at the time of function
execution. 每当执行使用父级作用域中任何变量的任何
function
,它都会获取function
执行时所持有的变量的值。 In your case i
is already reached to 10
at the time of execution because of i++
. 在你的情况
i
已经达到10
在执行的时候,因为i++
。
For getting expected result, you can add IIFE
to it, which will hold the value of i
in its scope. 为了获得预期的结果,您可以向其中添加
IIFE
,它将在其范围内保留i
的值。
var foo = []; for (var i = 0; i < 10; i++) { foo[i] = (function(i) { return function() { return i; }; })(i); }; console.log(foo[0]()); console.log(foo[1]()); console.log(foo[2]());
You can use this syntax which keeps the context 您可以使用保留上下文的此语法
for (let i = 0; i < 10; i++) {
foo[i] = () => i;
};
console.log(foo[0]());
console.log(foo[1]());
console.log(foo[2]());
https://jsfiddle.net/bandpay/8zat3bnn/ https://jsfiddle.net/bandpay/8zat3bnn/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.