我正在阅读《JavaScript语言精粹》,但对于这里到底发生了什么感到非常困惑。如果有更详细和/或简化的解释,那将不胜感激。
// BAD EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the wrong way.
// When you click on a node, an alert box is supposed to display the ordinal of the node.
// But it always displays the number of nodes instead.
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (e) {
alert(i);
}
}
};
// END BAD EXAMPLE
add_the_handlers
函数旨在为每个处理程序分配一个唯一的编号(i)。它失败了,因为处理程序函数绑定到变量i,而不是在函数创建时的变量i的值:
// BETTER EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the right way.
// When you click on a node, an alert box will display the ordinal of the node.
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);
};
}(i);
}
};
现在,我们不再将一个函数分配给 onclick ,而是定义一个函数并立即调用它,同时传递 i
。该函数将返回一个事件处理程序函数,它绑定到传入的 i
值,而不是绑定到在 add_the_handlers
中定义的 i
。返回的函数被分配给 onclick。