开发者

What are some simple cases where "closure" can be best demonstrated in javaScript [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do JavaScript closures work?

I still battle开发者_StackOverflow社区 with the concept of closure and when I need to implement it. I usually get there after trial and error, but I feel if I had some simplified representations of it's use with a clear explanation, I could preempt rewriting scripts to include it. Does anyone want to take a shot at clearing up an often confusing concept?


Nathan's Lessons may clear up your confusions, if you are looking for simple explanation.


Consider this example:

 for(var j = 0; j < 10; j++)
 {
     setTimeout(function()
     {
         alert(j);
     }, 1000);
 }

A closure wraps the reference to the variable so it can access it when the function is invoke. In the above example, every call captures the same reference to j; ergo all functions capture the same reference and all will alert '10'. Now consider this example:

 for(var j = 0; j < 10; j++)
 {
     var innerReference = j;
     setTimeout(function()
     {
         alert(innerReference);
     }, 1000);
 }

In this example, each iteration of the loop captures the reference to the newly created 'innerReference' variable; and each iteration creates a new innerReference. Ergo, this time they display 1, 2, 3, 4, etc and so forth.

At a basic level, it's pretty much like this; a closure is the capture of a reference to another variable outside to what would normally be the scope of that object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜