Goal "Self Invoking Anonymous Functions"

Possible duplicate:
What is the purpose of the self-executing function in javascript?

Hopefully a straightforward question:

What is the purpose of using self-naming anonymous functions? Is it just to prevent the "pollution" of the global sphere by variables, etc.? Or are there other benefits to using them?

+5
source share
4 answers

From my personal experience, in addition to using anonymous functions to induce a region, I also used it for for-loops to close. This can be useful when the DOM element needs to store its account and you do not have access to libraries like jQuery etc.

, 100 DIV . DIV 1, 56- div, 56.

, , -

// 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 );
    };
}

99, 99. i .

, ,

for (var i = 0; i < 100; ++i) {
    (function(count){
     myElements[count].onclick = function() {
         alert( 'You clicked on: ' + count );
     }; 
    })(i);
}

i .

+10

"" ..?

. .

+4

He must create his own realm. This is not only better, because you no longer “pollute” any other (global, for example) area, it gives you a guaranteed escape for problems with name collisions and protection against programmers who like to put too much inside their functions / objects / methods among all the benefits. It also allows the GC to easily understand that you no longer need any reference objects when the function is executed.

+3
source

Closures in for-loops also use self-naming 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);
    }
}
0
source

All Articles