javascript - 具有作用域问题的匿名函数调用

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

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

最佳答案

你可以像这样使用 IIFE:

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

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

关于javascript - 具有作用域问题的匿名函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17346492/

相关文章:

javascript - 原型(prototype)函数声明

php - JQuery 在 IE 8 或 7 中不起作用

javascript - 链接到蓝图 CSS 选项卡?

go - 比较 Go 中的函数值

java - Java中的匿名类和闭包有什么区别?

javascript - 如何访问 Aurelia 中自定义元素中的变量?

javascript - 在 Material-ui 和 Radium 中使用多种样式的问题

python - 内部函数未形成闭包

php - 在不引用 Closure 内部类的情况下测试 PHP Closure

Swift 4 闭包 : failing to access another local property from within the closure