不要在循环中创建函数 [英] Don't make functions within a loop
本文介绍了不要在循环中创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这种情况下解决jslint错误的正确方法是什么?我正在为使用它的对象添加一个getter函数。我不知道怎么做而不在循环内创建函数。
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.
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_;
}
};
}
推荐答案
将函数移出循环:
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
};
}
...或者只是使用 loopfunc
选项位于文件顶部:
... Or just ignore the message by using the loopfunc
option at the top of the file:
/*jshint loopfunc:true */
这篇关于不要在循环中创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文