Language Features – What Is a Closure?

closureslanguage-features

Every now and then I see "closures" being mentioned, and I tried looking it up but Wiki doesn't give an explanation that I understand. Could someone help me out here?

Best Answer

(Disclaimer: this is a basic explanation; as far as the definition goes, I'm simplifying a little bit)

The most simple way to think of a closure is a function that can be stored as a variable (referred to as a "first-class function"), that has a special ability to access other variables local to the scope it was created in.

Example (JavaScript):

var setKeyPress = function(callback) {
    document.onkeypress = callback;
};

var initialize = function() {
    var black = false;

    document.onclick = function() {
        black = !black;
        document.body.style.backgroundColor = black ? "#000000" : "transparent";
    }

    var displayValOfBlack = function() {
        alert(black);
    }

    setKeyPress(displayValOfBlack);
};

initialize();

The functions1 assigned to document.onclick and displayValOfBlack are closures. You can see that they both reference the boolean variable black, but that variable is assigned outside the function. Because black is local to the scope where the function was defined, the pointer to this variable is preserved.

If you put this in an HTML page:

  1. Click to change to black
  2. Hit [enter] to see "true"
  3. Click again, changes back to white
  4. Hit [enter] to see "false"

This demonstrates that both have access to the same black, and can be used to store state without any wrapper object.

The call to setKeyPress is to demonstrate how a function can be passed just like any variable. The scope preserved in the closure is still the one where the function was defined.

Closures are commonly used as event handlers, especially in JavaScript and ActionScript. Good use of closures will help you implicitly bind variables to event handlers without having to create an object wrapper. However, careless use will lead to memory leaks (such as when an unused but preserved event handler is the only thing to hold on to large objects in memory, especially DOM objects, preventing garbage collection).


1: Actually, all functions in JavaScript are closures.

Related Topic