17

I'm a web developer, but lots of folks are looking for slightly more advanced skills and understanding closures seems to be at the forefront of this.

I get the whole "execution context creating a reference to a variable that doesnt ever get destroyed" thing, but really, is this some sort of private or static variable implementation in JavaScript?

qodeninja
  • 10,946
  • 30
  • 98
  • 152

3 Answers3

14

They can be good for lots of things, for example, visibility (like private members in traditional OO).

var count = function(num) {

   return function(add) {
       add = add || 1;
       num += add;
       return num;
   }

}

See it.

My count() can be seeded with a number. When I assign a variable to the return, I can call it with an optional number to add to the internal num (an argument originally, but still part of the scope of the returned function).

This is a pretty good overview.

See also on Stack Overflow

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
5

A closure is a code block with bound variables - it "catches" its variables from their outer context - but it is independent from that same context.

A practical use in javascript is when defining events or callbacks - you declare a closure to be executed on the click of a button, for instance, but this closure can reference variables declared on the caller scope.

jQuery uses closures a lot - btw this is a good link for understanding closures for jQuery: A Graphical Explanation Of Javascript Closures In A jQuery Context.

Hope it helps.

rsenna
  • 11,775
  • 1
  • 54
  • 60
0

There are many JS books available, but you really should grab a copy of David Flanagan's JavaScript: The Definitive Guide if you really want to learn this (still the best JS reference IMHO). Read the chapter on closures and you'll get a lot more in-depth knowledge than anyone can give you in a reply here.

Brian Moeskau
  • 20,103
  • 8
  • 71
  • 73
  • The question is asking for specific topic if you can elaborate here. If posted a description with a good example could help a lot. – Santosh Dec 29 '16 at 14:02