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" as a keyword is only used for defining functions, and cannot be used inside a loop (or inside an "if" or "switch" or other control statement.) The only kinds of functions that can be defined within loops are anonymous functions.
JavaScript supports different kinds of loops: for - loops through a block of code a number of times. for/in - loops through the properties of an object. for/of - loops through the values of an iterable object.
We can even call a function inside from a loop as well. The function will be called each time the loop executes and will stop calling once the loop finishes. In this section, we see how we call a function from a loop.
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With