Tuesday, April 26, 2011

Skilldrick » Closures explained with JavaScript

Skilldrick » Closures explained with JavaScript: "Closures are functions that retain a reference to their free variables
And this is the meat of the matter. Let’s look at a simplified version of the above example first:


It’s no surprise that when you call f with the argument 5, when g is called it has access to that argument. What’s a bit more surprising is that if you return g from the argument, the returned function still has access to the argument 5 (as shown in the original example). The bit that can be a bit mind-blowing (and I think generally the reason that people have such trouble understanding closures) is that the returned g actually is remembering the variable x that was defined when f was called."