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:

  1. The Code to execute on completion
  2. The number of milliseconds before executing Arg1
Since I was several layers inside the AutoSave object, I addressed the function as this.doSave(). The problem arose that the execution context of setTimeout means that 'this' will not resolve into my handy doSave function. I could have addressed the function by the global variable containing my AutoSave object, but that would reduce the reusability of my JavaScript object.

What I needed was a way to maintain the variables from one scope into another scope and that is where the closure came in.

view plain print about
1startTimer : function(){
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.

view plain print about
1function(){ _OnTimeoutEnd()}

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.

Add Comment Subscribe to Comments

5/22/07 9:43 AM # Sez Nathan Mische

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.


5/22/07 9:51 AM # Sez Dan Wilson

@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


5/22/07 10:11 AM # Sez Nathan Mische

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.