JavaScript 不支持带有局部变量的闭包吗? [英] Doesn't JavaScript support closures with local variables?
问题描述
我对这段代码很困惑:
var closures = [];
function create() {
for (var i = 0; i < 5; i++) {
closures[i] = function() {
alert("i = " + i);
};
}
}
function run() {
for (var i = 0; i < 5; i++) {
closures[i]();
}
}
create();
run();
根据我的理解,它应该打印 0,1,2,3,4
(这不是闭包的概念吗?).
From my understanding it should print 0,1,2,3,4
(isn't this the concept of closures?).
而是打印5,5,5,5,5
.
我尝试了 Rhino 和 Firefox.有人可以向我解释这种行为吗?
I tried Rhino and Firefox. Could someone explain this behavior to me?
推荐答案
通过添加额外的匿名函数修复了 Jon 的答案:
Fixed Jon's answer by adding an additional anonymous function:
function create() {
for (var i = 0; i < 5; i++) {
closures[i] = (function(tmp) {
return function() {
alert("i = " + tmp);
};
})(i);
}
}
解释是 JavaScript 的作用域是函数级的,而不是块级的,创建闭包只是意味着将封闭作用域添加到封闭函数的词法环境中.
The explanation is that JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.
循环结束后,函数级变量i
的值为5
,这就是内部函数看到"的.
After the loop terminates, the function-level variable i
has the value 5
, and that's what the inner function 'sees'.
附带说明:您应该注意不必要的函数对象创建,尤其是在循环中;效率低下,如果涉及到 DOM 对象,很容易创建循环引用,从而在 Internet Explorer 中引入内存泄漏.
As a side note: you should beware of unnecessary function object creation, espacially in loops; it's inefficient, and if DOM objects are involved, it's easy to create circular references and therefore introduce memory leaks in Internet Explorer.
这篇关于JavaScript 不支持带有局部变量的闭包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!