【问题标题】:anonymous function calls with scoping issues [duplicate]具有范围问题的匿名函数调用[重复]
【发布时间】:2013-06-25 03:38:37
【问题描述】:

我确定以前有人问过这个问题,但我不知道要搜索什么。

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

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]);
}

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

【问题讨论】:

  • 不要使用 for ... in 在 JavaScript 中遍历数组。请改用索引变量和简单的for 循环。
  • 这个问题有很多很多重复。这是 JavaScript 中一个极其常见的陷阱。
  • 这就是为什么我注意到我确信以前有人问过它。我只是对 JS 不够熟悉,不知道如何正确处理它,或者搜索什么。
  • 别难过——我不是故意要批评的。可能很难找到重复项,因为相同的基本问题以许多不同的方式表现出来。归结为 JavaScript 范围仅在函数级别,因此像 Sirko 发布的技巧是必要的。

标签: javascript closures


【解决方案1】:

你可以像这样使用 IIFE:

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

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

【讨论】:

  • 这就是我要找的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 2014-09-11
  • 2012-02-23
相关资源
最近更新 更多