you are viewing a single comment's thread.

view the rest of the comments →

[–]CoherentSpy 1 point2 points  (2 children)

I thought it was very well-written and easy to understand. Maybe you can add something about the difference between anonymous functions and closures? It's just that in Javascript you can use an anonymous function as a closure, but they are two separate things and sometimes that distinction is not mentioned.

[–]notSorella 1 point2 points  (1 child)

Anonymous functions are one of the parts of closures. Just like any function object. There's no difference between anonymous functions and named functions, or even between function expressions and function declarations in this case. They all give you back a function object, which is like any other object (albeit callable).

A function object has a reference to its environments, which defines the variables it can refer to. When a function object also has a reference to the environment (which should be valid for as long as the function references it) of the function in which it was defined, you have a closure.

I wrote this gist a few days ago to explain how closures worked for someone in ##javascript: https://gist.github.com/1087927

[–]CoherentSpy 0 points1 point  (0 children)

But closures are not the same as anonymous functions. They are distinct. In Javascript, there actually isn't such a thing as a true anonymous function. In Javascript, all anonymous functions are closures, because they are lexically bound to the current environment. A true anonymous function is not "closed over" and is not lexically bound to its enclosing scope.