What is a JavaScript Closure, Anyway?
December 10, 2011 at 2:15 PM
—
Administrator
Back in the late nineties, during the .com boom, I worked on a huge web application that used XmlHttp (now known as AJAX) and extensive lots of JavaScript. The language and how it's perceived has changed a lot since then and so has the maturity of the community using it. Techniques have come about that make JavaScript easier to use in large internet applications. Most of these techniques have come about because developers are learning to go with the flow of the language instead of fighting it; to use the unique qualities of the language to advantage.
An Example
Consider the following JavaScript:
1: function MyClass(x) {
2: var Addend = x;
3:
4: return AddTo = function (y) {
5: return y + Addend;
6: }
7: }
8:
9: var AddToTen = MyClass(10);
10: alert(AddToTen(10));
11:
12: var AddToFive = MyClass(5);
13: alert(AddToFive(10));
Beginning in line 1, a function is being defined. Inside this function, we define a local variable and set its value equal to the passed in parameter. Then, an inner function is returned. This inner function refers to the local variable defined in the outer function. Once the outer function has completed execution, it cannot be garbage collected because it is still being referred to by the inner function. It's also very important to understand that whatever value the local variable has at the time the inner function is returned, is the value that will be visible to the inner function when it is executed from an external call.
When lines 9 and 10 run, 10 is passed in to the outer function and the local variable is set to 10. When the inner function is returned, it will always see Addend as having the value of 10. Thus, this script will pop the first alert with a value of 20 and then a second with the value of 15.
In short, whenever an inner function is returned from an outer one, a logical copy of the outer functions state is made available to the inner function and this state can be accessed each time the inner function is invoked.
What About a .Net Example
We can duplicate this behavior in C#. I created a Console application to illustrate this.
class Program
{
static void Main(string[] args)
{
var five = MyMethod(5);
Console.WriteLine(five(10));
var ten = MyMethod(10);
Console.WriteLine(ten(10));
Console.ReadLine();
}
static Func<int, int> MyMethod(int x)
{
int addend = x;
return new Func<int, int>((y) =>
{
return addend + y;
});
}
}