我正在阅读“Javascript: The Good Parts”一书中关于闭包的内容。
有以下使用闭包的例子:
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (i) {
return function (e) {
alert(i + ":" + e);
};
}(i);
}
};
这是正确的例子吗?或者下面是更正确的例子?
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (idx) {
return function (e) {
alert(idx + ":" + e);
};
}(i);
}
};
外部函数中的变量 i 和内部函数“nodes[i].onclick = function (i)”中的变量 i - 这是两个不同的变量。
第三个函数从第二个函数访问变量,而不是从最外层访问变量。
我说得对吗?
最佳答案
这两个例子是相同的。闭包的全部意义在于将一个外部作用域变量 (i) 变成一个内部作用域变量(i/idx/foo,随您选择)。闭包创建变量的“副本”,以便在进行回调时,它具有正确的值。
// outer-scoped i changes on each iteration
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (i) {
// here i now refers to a different variable; while the outer i keeps iterating,
//this i is preserved at its current value.
return function (e) {
alert(i + ":" + e);
};
}(i);
}
关于javascript - "Javascript: The good parts"中的闭包示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11095493/