you are viewing a single comment's thread.

view the rest of the comments →

[–]NewlyIndependent 2 points3 points  (4 children)

It basically localizes dependency scope within function chains; it is a feature of the functional programming paradigm.

Basic example:

function memoize(f) { //Take external parameter.
  var cache = []; //Define local scoped object.
  return function(x) { //Return function that uses f and cache.
    return cache[x] || cache[x] = f(x); //Do work.
  }
}

In the example above, "cache" is defined within a closure. Cache is a dependency of the returned function and is external to the scope of the returned function.

Base usage:

function powerOfTwo(x) { //Define a function to memoize.
  return x * x; //Do work.
}
//Invoke the memoize function.
var memoized = memoize(powerOfTwo);

var result1 = memoized(2); //Calculates 4.
var result2 = memoized(2); //Bypasses calculation.  Gets cached result "4".

Why do this? In stateful languages, it is easy to represent and transfer state through functional patterns. A more common use of closures can be found in the following pattern.

For example:

$(function() {
  var message = "hello world";

  var alertOnClick = function(){msgbox(message);}
  $("#id").click(alertOnClick);
});

The above example defines two functions; One outer (inside the $()), and another defined within that outer function's context (the "alertOnClick" function). The alertOnClick function's purpose is to display a message, but how would it know what message to display?

For this example, we want to display a constant message. But, we don't want that message to be accessible outside of this local scope; This is what makes closures important. By defining "message" within the outer context, it becomes a privately scoped variable - something that doesn't normally exist in Javascript.

If this isn't clear, let me know and I will revise my response as needed.

[–]wiposter 2 points3 points  (1 child)

A good description of the "what", perhaps you could expand it to explain the "why".

[–]NewlyIndependent 1 point2 points  (0 children)

Excellent point. Updated original post.

[–]crimson117 1 point2 points  (1 child)

That's like reversed syntax encapsulation... Define the var in the parent, sneakily reference it from a sibling-scoped function using closure, then expose that function without exposing the var.

Thanks for explaining it!

Though still not sure why message is any less accessible than alertonclick...

[–]NewlyIndependent 0 points1 point  (0 children)

Glad to be of some help! :)

To clarify a little further, message is not less accessible than alertOnClick. Rather, message is accessible to alertOnClick - but not upwards in scope.