开发者

Javascript closure

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

thanks.

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.len开发者_如何学Cgth;i<len;++i){
            anotherFn(a[i]);
}


In this example there are no differences. In both cases, anotherFn gets 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]);
    }
}

As JavaScript has only function scope, no block scope, all the event handlers share the same i, which will have the value 10 after the loop finished. So every handler will try to alert values[10].

By using an immediate function, a new scope is introduced which "captures" the current value of the loop variable:

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

As this is sometimes hard to read, creating a standalone function which returns another function is often better:

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

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


In both instances in your example the values do identical operations. There are other examples out there where if you're not careful to use the first method (with the self-executing anonymous function), the value of i will increment and not be passed correctly to your function.

Here's a guide, scroll down to the creating closures in loops: a common mistake section to see the problem:

https://developer.mozilla.org/en/JavaScript/Guide/Closures


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜