在事件闭包中访问可变变量

jed*_*ikb 6 javascript closures javascript-events mousetrap

我试图使用mousetrap javascript插件以类似的方式处理一些关键笔划,所以我想将它们编码如下:

    var keys = [ 'b', 'i', 'u'];
    for (var i=0; i < 3; ++i) {
        var iKey = keys[i];
        var iKeyUpper = iKey.toUpperCase();

        Mousetrap.bind(
            [   'command+' + iKey,
                'command+' + iKeyUpper,
                'ctrl+' + iKey,
                'ctrl+' + iKeyUpper],
            ( function( e ) {
                console.log( "you clicked: " + i );
        } ) );

    }
Run Code Online (Sandbox Code Playgroud)

但是,显然,i是可变的.但是,我不知道如何编写一个闭包,我在响应中竞争事件参数.关于如何处理这种情况的建议?

Ber*_*rgi 5

如何编写一个闭包,我在响应中竞争事件参数

在整个循环体周围使用闭包(如@dandavis所示),或仅在处理程序周围使用它:

…
    Mousetrap.bind(
        [   'command+' + iKey,
            'command+' + iKeyUpper,
            'ctrl+' + iKey,
            'ctrl+' + iKeyUpper],
        (function(_i) { // of course you can use the name `i` again
            return function( e ) {
                console.log( "you clicked: " + _i );
            };
        })(i) // and pass in the to-be-preserved values
    );
Run Code Online (Sandbox Code Playgroud)