3

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?

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • 1
    I've just written a [blog post](http://skilldrick.co.uk/2010/11/a-brief-introduction-to-closures/) about closures in JavaScript that you may find helfpul. – Skilldrick Nov 23 '10 at 14:48

3 Answers3

11

Searching for "javascript closures" gave plenty of encouraging-looking links. The top three were these two (the third link was a reformatted version of the second):

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 :)

Travis J
  • 81,153
  • 41
  • 202
  • 273
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @sunglim: It would have helped if you'd said *which* link wasn't valid. Anyway, fixing. – Jon Skeet Apr 07 '10 at 14:13
  • Links 1 and 3 are the same article. – Yarin Nov 17 '10 at 18:29
  • Anyone can google "encouraging" links, but the user was looking for direction from the OS community. If you haven't used the resources yourself don't recommend them. – Yarin Nov 17 '10 at 18:33
  • @Yarin: The OP *specifically* asked for "an example of how this applies". The linked pages give plenty of examples. While anyone *can* search for links, it seems to me that lots of people *don't*. I think you meant that 2 and 3 are the same article - albeit reformatted. I'll remove the third link. – Jon Skeet Nov 17 '10 at 19:03
4

(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.

1

A practical example of closures is when they are used to create "Private" variables, like

function incrementer(){
    var i=0;
    this.increment=function(){
        i++;
    }
    this.get=function(){
        return i;
    }
}

The only way to access i is to use the method get, and the only way to change it is to use the method increment. In classes, you can do this to emulate private variables.

invisible bob
  • 864
  • 1
  • 9
  • 24