Friday, December 28, 2007

Closures

What are Closures?

  • a function that is evaluated in an environment containing bound variables that can be accessed by the function
  • allows inner functions - functions that are inside the body of other functions

An example...

  // Return a function that approximates the derivative of f
// using an interval of dx, which should be appropriately small.
function derivative(f, dx) {
return function(x) {
return (f(x + dx) - f(x)) / dx;
};
}


  • The closure outlives the scope of the function that creates it, the variables f and dx live on after the function returns
  • In languages without closures, the lifetime of a local variable coincides with the execution of the scope where that variable is declared. In languages with closures, variables must continue to exist as long as any existing closures have references to them

Closures on Wikipedia
JavaScript Closures
The Closures Controversy

No comments: