Using Closures in Javascript
Closures in JavaScript are a very important tool. The ability to control the execution contexts of variables and functions gives a lot of power. In some cases, closures aren't only handy and powerful, they are necessary. For example, in the process of wrapping up a JavaScript AutoSave, I ran into a bit of a scoping problem with setTimeout().
As you know, setTimeout hangs off of the 'window' scope. The fully qualified call is window.setTimeout(). Inside of my javascript object I created a setTimeout command to run the doSave() function. The setTimeout() function takes two arguments:
- The Code to execute on completion
- The number of milliseconds before executing Arg1
What I needed was a way to maintain the variables from one scope into another scope and that is where the closure came in.
2 if (! _timerRunning){
3 var _OnTimeoutEnd = this.doSave;
4 _timer = setTimeout ( function(){ _OnTimeoutEnd()}, _SaveCycleLength );
5 _timerRunning = true;
6 }
7},
This piece is specifically the closure.
Notice above how I get a reference to the function doSave from the this scope. Inside the AutoSave object, 'this' points to the AutoSave object. Then I set this.doSave to a new variable which I then put inside the first argument of setTimeout.
When this code executes, _OnTimeoutEnd correctly resolves to the AutoSave.doSave function and the save is completed.
JavaScript closures are very powerful and should become a part of your toolbox as well. If you would like to read more about Closures in JavaScript, I suggest Javascript Closures
by Richard Cornford.
There are no comments for this entry.
@Nathan,
That is exactly the problem I had. The point of the closure is to maintain the state of the variable. Since I use 'this' to refer to the variable and it is inside of a closure, when the code is executed by the setTimeout function it refers to the intended scope.
As my post above states as well as your documentation link, setTImeout executes in a different execution context. The closure is needed to maintain the correct pointer.
Does that make sense?
DW
Hey Dan, that makes sense. I guess I'm just not following your example. I'm going to try messing around with your code this evening to see if I can get the light bulb to go off.





Sez : Dan Wilson
May 21, 2007 2:56 PM
Suscribe
Follow Us
Contact
JavaScript closures are indeed powerful, but I'm not sure what you are showing here is a valid example. (I am new to this closure stuff so I could be wrong.) I think what you are running into is the 'this' problem (http://developer.mozilla.org/en/docs/DOM:window.se...). Could you maybe show a simple working example of the issue? Without seeing a complete AutoSave object it hard to tell what issue your current example is solving.