Search code examples
javascriptjslint

Don't make functions within a loop


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

Solution

  • 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 */