使用IIFE时,避免在循环中定义函数

Mat*_*son 2 javascript jshint

我有以下代码:

for (i = 0; i < 5; i++) {
    this.hands[0].cards[i].img.on('mousedown', (function (i) {
        var j = i;
        return function (event) {
            self.hands[0].cards[j].holdCard();
        };
    })(i));
}
Run Code Online (Sandbox Code Playgroud)

这对我的需求很好,但JSHint抱怨:

[L1164:C10] W083:不要在循环内执行功能.

如何通过不同的方式重写JSHint来保持高兴?

bfa*_*tto 6

您可以使用循环外部的单独功能替换IIFE:

function createHandler(j, self) {
    return function (event) {
        self.hands[0].cards[j].holdCard();
    };
}
for (i = 0; i < 5; i++) {
    this.hands[0].cards[i].img.on('mousedown', createHandler(i, this));
}
Run Code Online (Sandbox Code Playgroud)

有用的参考:JSLint错误说明(感谢用户链接的1671639).

  • +1在我做一个jsfiddle之前你得到了它.这里也有很好的解释错误[JSLint错误说明](http://jslinterrors.com/dont-make-functions-within-a-loop/) (2认同)