O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 }

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required