Google Maps API Tutorial

© 2006, 2007, 2008, 2009 Mike Williams

 
Translate this page:

 

Javascript Concepts: Function Closure

Function closure is a fairly unusual computer language concept so it may take you by surprise if you're familiar with other programming languages.

What happens is that each time a function closes, a copy of the values of its local variables is retained. Technically, a copy of the function's "activation frame" is retained, and that contains all the local variables.

The key feature of function closure is that any callback functions (such as event handlers) which were created when the function executed will have access to the preserved activation frame, and its local variables.

Activation Frame

Activation frames do occur in other languages that support recursive functions. Consider this code
    function factorial(a) {
      if (a == 1) {return 1}
      else {return a*factorial(a-1)}
    }
When you call "factorial(5)", then five separate instances of the factorial() function get executed, each one has its own activation frame, which contains its own local variables. In particular, each instance of the function has its own value for "a".

Memory

If a function closes without creating a callback function, then, in a properly written browser, its activation frame will eventually be destroyed by the Garbage Collection system, and the memory recovered.

The variables are only retained if something continues to hold accessible references to them.

Closure

Note that the value of the variable that is retained is the value at the time that the function closed, not the value at the time that the callback function was created.

Updating closure variables

A callback function can change the values of variables in the activation frame of the closed function. It can't, however, create new variables in that activation frame.
   function f1() {
      var foo=123;
      GEvent.addListener(map,"click",function(overlay,point) {
        GLog.write(foo);
        foo++;
      });
      var foo=321;
    }
The first time the map is clicked, the value "321" will be displayed (the value of "foo" when the function closed).

The second time the map is clicked, the value "322" will be displayed. The value of "foo" in the activation frame has been updated by the previous click callback.

Back to Mike's Homepage
Up to the start of this tutorial