Possible Duplicate:
What is the purpose of a self executing function in javascript?
Hopefully quite a straight forward question:
What is the purpose of using self invoking anonymous functions? Is it simply to prevent “polluting” the global scope with variables etc.? Or are there other advantages to using them?
Out of my personal experience, other than using anonymous functions for inducing a scope, I have also used it in for-loops for closure. This can be useful when a DOM element needs to store its count and you don’t have access to libraries like jQuery etc.
Let’s say you have a 100
DIVelements. Clicking the firstDIVelement should alert 1, similarly clicking the 56th div element should alert 56.So when creating these elements, you normally do something like this
This will alert 99, as the counter is currently 99. The value of
iis not maintained here.However, when an anonymous function is used to tackle the problem,
Here the value of
iis maintained and the correct count is displayed.