The purpose of “Self Invoking Anonymous Functions” [duplicate]

*爱你&永不变心* 提交于 2019-12-09 17:28:18

问题


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?


回答1:


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.




回答2:


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.




回答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.




回答4:


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


来源:https://stackoverflow.com/questions/10831724/the-purpose-of-self-invoking-anonymous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!