简体   繁体   English

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

[英]Avoid defining a function in a loop when using an IIFE

I have the following following code: 我有以下代码:

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));
}

This is working fine for my needs but JSHint is complaining: 这可以满足我的需求,但是JSHint抱怨:

[L1164:C10] W083: Don't make functions within a loop. [L1164:C10] W083:请勿在循环内执行功能。

How can I keep JSHint happy by rewriting this differently? 如何通过以不同的方式重写JSHint来保持满意?

You can replace the IIFE with a separate function outside the loop: 您可以在循环外用单独的函数替换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));
}

Useful reference: JSLint Errors Explanation (thanks to user1671639 for the link). 有用的参考: JSLint错误说明 (感谢user1671639的链接)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM