tags:

views:

129

answers:

4

I am relatively new to Javascript. I understand the concept of anonymous functions - but closures seem less clear. The similarity between the two (in my mind atleast), is confusing.

Could someone explain the difference? (preferrably, with some code snippet, to illustrate the points clearer).

+3  A: 

Have you seen this article? http://www.jibbering.com/faq/faq_notes/closures.html

This could also be good as a starting point: http://www.javascriptkit.com/javatutors/closures.shtml

naivists
+1 for the comp.lang.javascript FAQ link.
Tim Down
+3  A: 

I explained this here: The Zen of Closures.

Basically, without going into technical details:

  • an anonymous function is a function without a name (that can be assigned to variables).
  • a closure is a kind of private global variable
slebetman
+2  A: 

The important difference is that a closure captures the scope it was defined in.

In other words, a closure may access variables and their state even though they belong to the closure's parent scope (e.g. the function the closure was created in). This allows closures to capture and "transport" application state around your program.

An anonymous function cannot do that; its reach is limited to variables defined inside its body and signature (i.e., its parameters).

EDIT: Just to clarify: In JavaScript it is especially unclear since there is no language construct called closure. You'd still use an anonymous function for that. I was only referring to the conceptual difference.

Matthias
A: 

I found this SO answer, which put it very clear for me:

http://stackoverflow.com/questions/50255/does-java-need-closures/716763#716763

OscarRyz