不要在循环中创建函数[重复]

时间:2022-08-17 20:03:54

This question already has an answer here:

这个问题已经有了答案:

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

1 个解决方案

#1


93  

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 loopfunc option at the top of the file:

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

/*jshint loopfunc:true */

#1


93  

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 loopfunc option at the top of the file:

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

/*jshint loopfunc:true */