【问题标题】:Access array element from parent scope within inner function [duplicate]从内部函数中的父范围访问数组元素[重复]
【发布时间】:2014-07-13 21:27:27
【问题描述】:

在下面的代码中,我尝试创建几个处理函数,它们必须调用存储在函数数组('buttonHandlers')中的不同函数。这个数组是外部作用域的一部分:

buttonJson = {};
for (i = 0; i < buttonNames.length; i++) {
    customHandler = buttonHandlers[i];
    buttonJson[buttonNames[i]] = function() {
        customHandler.apply();
        $('#msg-dialog-confirm').dialog("close");
        $('body').remove('#msg-dialog-confirm');
        ...
    };
}

上面的代码生成了调用函数数组的最后一个数组元素('buttonHandlers')的处理函数。我希望每个处理函数只调用相关数组索引指定的关联函数。我怎样才能做到这一点?

【问题讨论】:

  • 试试buttonJson[buttonNames[i]] = function(customHandler) {
  • 它不起作用。可能,这个提示太短了。无论如何,我需要将函数传递给这个参数。

标签: javascript arrays scope closures


【解决方案1】:

customHandler 是一个全局变量,您在每次迭代时都会覆盖它,您应该创建一个新作用域来锁定该值

buttonJson = {};
for (i = 0; i < buttonNames.length; i++) {
    (function(button) {
        buttonJson[button] = function() {
            button.apply();
            $('#msg-dialog-confirm').dialog("close");
            $('body').remove('#msg-dialog-confirm');
            ...
        };
    })(buttonHandlers[i]);
}

【讨论】:

  • 谢谢!这就像一个魅力!此外,我们还必须传递来自buttonNames[i] 的值并将其用作键值:buttonJson[text]
猜你喜欢
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多