8

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?

Community
  • 1
  • 1
Nealbo
  • 529
  • 4
  • 20

4 Answers4

11

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.

supertonsky
  • 2,563
  • 6
  • 38
  • 68
Ashwin Krishnamurthy
  • 3,750
  • 3
  • 27
  • 49
4

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

It is to create its own scope. It is not only better because you no longer "pollute" some other (global, for example) scope, it gives you guaranteed escape for name collision concerns and defense from programmers that like to poke inside internals of your functions/objects/methods too much among all the benefits. It also allows GC to easily understand that you don't need any of referenced objects anymore when function is done.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
0

Closures in for-loops also use self invoking anonymous functions.

function attachEventsToListItems( ) {
    var oList = document.getElementById('myList');
    var aListItems = oList.getElementsByTagName('li');
    for(var i = 0; i < aListItems.length; i++) {
        var oListItem = aListItems[i];
        // Watch this:
        oListItem.onclick = (function(value) {
            return function() {
                alert(value);
            }
        })(i);
    }
}
Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75