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?
What are Self-Invoking Anonymous Functions in JavaScript? In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to the namespace and control the visibility of member functions.
Parameters can also be passed to these Self invoked functions, generally, references to global objects are passed as parameters. Not too many arguments should be passed as functions become large and users need to scroll for the parameters. This Self Invoking function are mainly for variable scoping.
Both of those self-executing anonymous functions have same-named variables and methods. But they never complain that the variable is already declared. Thus it avoids clashes with other libraries and code blocks.
Many programmers use anonymous functions with the same gusto as that friend of yours who puts hot sauce on everything. Just because an anonymous function isn't needed to solve a problem doesn't mean that it shouldn't be used to solve the problem. Avoiding JavaScript code that uses anonymous functions is impossible.
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 DIV
elements. Clicking the first DIV
element should alert 1, similarly clicking the 56th div element should alert 56.
So when creating these elements, you normally do something like this
// Assume myElements is a collection of the aforementioned div elements
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = function() {
alert( 'You clicked on: ' + i );
};
}
This will alert 99, as the counter is currently 99. The value of i
is not maintained here.
However, when an anonymous function is used to tackle the problem,
for (var i = 0; i < 100; ++i) {
(function(count){
myElements[count].onclick = function() {
alert( 'You clicked on: ' + count );
};
})(i);
}
Here the value of i
is maintained and the correct count is displayed.
Is it simply to prevent "polluting" the global scope with variables etc.?
Pretty much. Encapsulation and avoiding as much global state as possible are good goals in themselves.
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