Javascript closure

I read () at the end of the close, will execute it immediately. So what is the difference between the two. I saw the first use in some code.

thank.

for (var a=selectsomeobj(),i=0,len=a.length;i<len;++i){
        (function(val){
            anotherFn(val);
        })(a[i]);
}

for (var a=selectsomeobj(),i=0,len=a.length;i<len;++i){
            anotherFn(a[i]);
}
+3
source share
3 answers

There are no differences in this example. In both cases it anotherFnis executed immediately.

However, an immediate function is often used when a function is created in a loop.

Consider this example (more or less pseudo-code):

for(var i from 1..10) {
    elements[i].onclick = function() {
         alert(values[i]);
    }
}

Because JavaScript has only a scope of functions, without a block scope, all event handlers have the same ione that will matter 10after the loop finishes. Therefore, each handler will try to warn values[10].

, , "" :

for(var i from 1..10) {
    (function(index) {
        elements[i].onclick = function() {
             alert(values[index]);
        }
    }(i));
}

, , , :

function getHandler(value) {
     return function(){alert(value);};
}

for(var i from 1..10) {
     elements[i].onclick = getHandler(values[i]);
}
+14

the first defines the self-invoking function (which, in turn, performs the function), the second simply performs this function. In both cases, the argument passed to a is a [i].

+1
source

All Articles