2.3. Closures / Anonymous Functions and Functions as Objects

In JavaScript, the definition:

function add(x,y)
{
      return x+y;
}

is equivalent to:

var add = function(x,y)
{
      return x+y;
}

Both create a variable named add to reference a function object. In the second version, however, the function is anonymous. The ability to create anonymous functions means that we can create specialized functions (or closures).

var createAdditionClosure = function(x,y)
{
      return function() {x+y;}
}

And then call this via:

var fn = createAdditionClosure(1,2);
var value = fn();

This ability allows us to capture contextual state and wrap it up into an event handler:

element.onClick = function() { // operations on current context }

Get Prototype and Scriptaculous: Taking the Pain out of JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.