Skip to content
Advertisement

Pass event to another function

JavaScript

Now with above code I am getting JShint error:

“Dont make functions within loop”.

To resolve above error I am doing this now:

JavaScript

Is this fine? If yes then how can I pass event from click event to clickHandler and then to doClick function?

Advertisement

Answer

No, it’s not fine. The problem in creating functions inside a loop is that you create a new copy of the function at each iteration.

In your second code, you call clickHandler at each iteration, which will return a different copy of the function each time. So it’s still the same problem.

Instead, a better way is creating the function only once before the loop, and reference it inside:

JavaScript

However, since events does not seem to depend on i, you can move it outside too:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement