问题
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_;
}
};
}
回答1:
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:
/*jshint loopfunc:true */
来源:https://stackoverflow.com/questions/10320343/dont-make-functions-within-a-loop