javascript:将局部变量传递给匿名函数

时间:2014-07-01 21:22:22

标签: javascript

问题:如何访问shortcutaction或其他本地变量

相关:类似问题,但没有成功:

Java解决方案:final修饰符设置为匿名函数中所需的变量

目标源代码:

//plugin.buttons is collection of button objects
for (var i in plugin.buttons) {
    var button = plugin.buttons[i];
    var icon = button.icon;
    var text = button.text;
    var shortcut = button.shortcut;
    var action = button.action; //action is a function ( or method )

    if (shortcut != null && shortcut.length > 0) {
        if ($.isFunction(action)) {
            console.log(shortcut); //it's valid shortcut
            //using jQuery hotkey plugin
            $('div[contenteditable]').bind('keydown', shortcut, function () {
                console.log(shortcut); //it's undefined
                action.call(); //it's undefined also
                return false;
            });
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以将其作为event data

传递
for (var i in plugin.buttons) {
    var button = plugin.buttons[i];
    var icon = button.icon;
    var text = button.text;
    var shortcut = button.shortcut;
    var action = button.action; //action is a function ( or method )

    if (shortcut != null && shortcut.length > 0) {
        if ($.isFunction(action)) {

            $('div[contenteditable]').on('keydown', {shortcut : shortcut}, function (e) {

                console.log(e.data.shortcut);

            });
        }
    }
}

但是在这种情况下,真正的问题是for循环中没有特殊的范围,因此在for循环中定义变量只会在每次迭代时覆盖相同的变量,这就是为什么它在工作时不起作用的原因。事件处理程序稍后调用。

您必须锁定新范围中的变量

for (var key in plugin.buttons) {
    (function(i) {
        var button = plugin.buttons[i];
        var icon = button.icon;
        var text = button.text;
        var shortcut = button.shortcut;
        var action = button.action; //action is a function ( or method )

        if (shortcut != null && shortcut.length > 0) {
            if ($.isFunction(action)) {
                console.log(shortcut); //it's valid shortcut
                //using jQuery hotkey plugin
                $('div[contenteditable]').bind('keydown', shortcut, function () {
                    console.log(shortcut); //it's undefined
                    action.call(); //it's undefined also
                    return false;
                });
            }
        }
    })(key);
}