JavaScript Closures for Dummies

Morris Johns has detailed “Closures” alongwith expamples “Closures Are Not Magic”. —This page explains closures so that a programmer can understand them - using working JavaScript code. It is not for gurus nor functional programmers. Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any […]

Morris Johns has detailed “Closures” alongwith expamples “Closures Are Not Magic”. —This page explains closures so that a programmer can understand them - using working JavaScript code. It is not for gurus nor functional programmers.

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

This article is intended for programmers with some programming experience in a main-stream language, and who can read the following JavaScript function:
function sayHello(name) { var text = 'Hello ' + name; var sayAlert = function() { alert(text); } sayAlert(); }

An Example of a Closure

Two one sentence summaries:

  • a closure is the local variables for a function - kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

The following code returns a reference to a function: function sayHello2(name) { var text = 'Hello ' + name; // local variable var sayAlert = function() { alert(text); } return sayAlert; }

Continue to read full post…

ajaxian

Closures, for Dummies