views:

437

answers:

2

From Wikipedia, the free encyclopedia: Closure (computer science)

In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Constructs such as objects in other languages can also be modeled with closures.

To use this inside of JavaScript, can someone point me to an example of how this applies?

+8  A: 

Searching for "javascript closures" gave plenty of encouraging-looking links. The top three were:

If these didn't help you, please explain why so we're in a better position to actually help. If you didn't search before asking the question, well - please do so next time :)

Jon Skeet
the link is not valid
sunglim
@sunglim: It would have helped if you'd said *which* link wasn't valid. Anyway, fixing.
Jon Skeet
+1 for JavaScript closures for dummies
Colonel Sponsz
+2  A: 

(using an example from jQuery)

function SetClassOnHover(className){
  $("td").hover(
    function () {
      $(this).addClass(className);
    },
    function () {
      $(this).removeClass(className);
    }
  );
}

The closure comes into play when the variable className is used inside the scope of each function. When SetClassOnHover exits, both functions must retain a handle on className in order to access its value when the functions are called. That's what the closure enables.

Will