不要在循环中创建函数

Thi*_*man 68 javascript jslint

在这种情况下解决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_;
       }
   };
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 105

将函数移到循环外:

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
   };
}
Run Code Online (Sandbox Code Playgroud)

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

/*jshint loopfunc:true */
Run Code Online (Sandbox Code Playgroud)

  • @AmolMKulkarni当函数表达式放在循环中时,它在每次迭代时构造.在循环外部移动函数表达式/声明有一些性能优势:http://jsperf.com/closure-vs-name-function-in-a-loop/2 (13认同)
  • @ 0x80`his`指向函数的上下文,在这种情况下是`results [i]`.http://jsfiddle.net/W5vfw/ (3认同)
  • 精彩!感谢您清楚地解释这一点.这是我在Javascript中从未感到自信的事情之一. (2认同)
  • 当您要将一些参数传递给函数时会发生什么? (2认同)