(Disclaimer: this is a basic explanation; as far as the definition goes, I'm simplifying a little bit)
The most simple way to think of a closure is a function that can be stored as a variable (referred to as a "first-class function"), that has a special ability to access other variables local to the scope it was created in.
Example (JavaScript):
var setKeyPress = function(callback) {
document.onkeypress = callback;
};
var initialize = function() {
var black = false;
document.onclick = function() {
black = !black;
document.body.style.backgroundColor = black ? "#000000" : "transparent";
}
var displayValOfBlack = function() {
alert(black);
}
setKeyPress(displayValOfBlack);
};
initialize();
The functions1 assigned to document.onclick
and displayValOfBlack
are closures. You can see that they both reference the boolean variable black
, but that variable is assigned outside the function. Because black
is local to the scope where the function was defined, the pointer to this variable is preserved.
If you put this in an HTML page:
- Click to change to black
- Hit [enter] to see "true"
- Click again, changes back to white
- Hit [enter] to see "false"
This demonstrates that both have access to the same black
, and can be used to store state without any wrapper object.
The call to setKeyPress
is to demonstrate how a function can be passed just like any variable. The scope preserved in the closure is still the one where the function was defined.
Closures are commonly used as event handlers, especially in JavaScript and ActionScript. Good use of closures will help you implicitly bind variables to event handlers without having to create an object wrapper. However, careless use will lead to memory leaks (such as when an unused but preserved event handler is the only thing to hold on to large objects in memory, especially DOM objects, preventing garbage collection).
1: Actually, all functions in JavaScript are closures.
Because javascript doesn't have feature like namespaces, and you can mess up pretty easily with all sort of global objects.
So it is important to be able to isolate some code in its own execution environment. Closure are perfect for that.
This usage of closure doesn't make sense in a language like C# where you have namespaces, classes and so on to isolates code and not putting everything in the global scope.
A very common practice for javascript code is writting it like this :
(function(){
// Some code
})();
As you can see, this is an anonymous function declaration, followed immediately by its execution. Thus, everything defined within the function is impossible to access from outside, and you will not mess up the global scope. The execution context of this function will remain alive as long as some code uses it, like nested functions defined within this context, that you can pass as callback or whatever.
Javascript is a very different language than C#. It's not object oriented, it is prototype oriented. This leads to very different practices at the end.
Anyway, closures are good, so use them, even in C#!
EDIT: After some discuss on stackoverflow's chat, I think this anwer has to be precised.
The function in the sample code isn't a closure. However, this fucntion can define local variable and nested functions. All nested functions that use these local variables are closures.
This is usefull to share some data across a set of functions without messing up the global scope. This is the most common use of closure in javascript.
Closure are way more powerfull than just sharing some data like this, but let's be realistic, most programmers don't know a thing about functionnal programming. In C# you would have used class or a namespace for these kind of use, but JS does not provide this functionnality.
You can do way more with closure than just protect the global scope, but this is what you'll see in JS source code.
Best Answer
No, not every function is a closure.
Wikipedia says:
I'd add "non-local and non-global", but the idea is correct.
Neither your C++ nor Python examples use closures. In both cases it's just scoping rules allow functions to see their outer scope and global scope.
"Closure" happens in the 1st example -
incrementBy
is constructed in and then returned from it's outer function, capturing argumentx
. When you assignvariable closure1 = startAt(1)
, you end up having a closure (function) insideclosure1
var which captured argument, which value happened to be1
, so when you callclosure1(2)
the result is3
(1
+2
).Think of it as memorizing some information about closure's declaration scope:
incrementBy
retain a memory about insides ofstartAt
, specifically a value of it's argumentx
.In lambda calculus, as I know, those "non-local" variables are called "free", and functions with free variables are called "open terms". Closure is a process of "closing" open terms by "fixing" values of those free variables in aforementioned "environment table". Hence the name.
It's worth noting that in Python and JS closure happens implicitly, while in PHP you have to explicitly tell which variables you want to close over (capture): http://php.net/manual/en/functions.anonymous.php - note
use
keyword in declarations: