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
Don't make functions within a loop
提问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 loopfunc
optionat the top of the file:
... 或者使用文件顶部的loopfunc
选项忽略该消息:
/*jshint loopfunc:true */