0

Possible Duplicate:
How do JavaScript closures work?

I still battle 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?

Community
  • 1
  • 1
AdrianB
  • 110
  • 1
  • 8

2 Answers2

2

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

suhair
  • 10,895
  • 11
  • 52
  • 63
1

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.

Tejs
  • 40,736
  • 10
  • 68
  • 86
  • 1
    I hate to niggle, but when I plug your second example into a webpage and test it (in IE8), it doesn't do what you'd hoped.... – Blazemonger Aug 19 '11 at 17:57
  • Interesting. You certainly are correct. I'd definitely take a look at @suhair's link – Tejs Aug 19 '11 at 18:13