Javascript 不要在循环中创建函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10320343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:51:00  来源:igfitidea点击:

Don't make functions within a loop

javascriptjslint

提问by Thijs Koerselman

What would be the correct way to solve the jslint error in this case? I'm adding a getter function to an object which uses this. I don't know how to do this without creating the function inside the loop.

在这种情况下,解决 jslint 错误的正确方法是什么?我正在向使用它的对象添加一个 getter 函数。如果不在循环内创建函数,我不知道如何做到这一点。

for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: function() { // TODO solve function in loop.
            return this.name_;
       }
   };
}

回答by Rob W

Move the function outside the loop:

将函数移出循环:

function dummy() {
    return this.name_;
}
// Or: var dummy = function() {return this.name;};
for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: dummy
   };
}

... Or just ignore the message by using the loopfuncoptionat the top of the file:

... 或者使用文件顶部的loopfunc选项忽略该消息:

/*jshint loopfunc:true */