带有范围问题的匿名函数调用

时间:2013-06-27 14:53:34

标签: javascript closures

我确定之前已经问过,但我不知道该搜索什么。

所以我希望使用与单击项目对应的字符串调用函数,但我想简单地将任何新项目添加到字符串数组中。

var menuList = ["overview", "help", "search"];
var functionCalls = [
  function() { toggleMenu(menuList[0]); },
  function() { toggleMenu(menuList[1]); },
  function() { toggleMenu(menuList[2]); },
];

在循环中使用如下:$("something").click(functionCalls[i])

这是我想要做的事情(但显然它不起作用):

for (var i in menuList) {

  // This does not work because the closure references 'i'
  // which, at the end, is always the index of the last element
  $("something").click(function() {
    toggleMenu(menuList[i]);
  });

  // this works, but I have to define each closure
  $("something").click(functionCalls[i]);
}

如何创建一个接受基于变量的值的匿名函数 - 但不保留对变量的引用?

1 个答案:

答案 0 :(得分:3)

您可以使用这样的IIFE:

for (var i=0; i<menuList.length; i++) {
  !function( index ) {
    $("something").click(function() {
      toggleMenu( menuList[index] ); 
    });
  }( i );
}

通过调用匿名函数,您可以为i创建名为index的当前值的本地副本。因此,所有处理程序都会收到各自版本的i

相关问题