I've read about closures many times here.
But I'm really confusing to know exactly what do closure mean?
- Is variable a closure ?
- Or, is function is a closure ?
- Or, both can be called a closure ?
I've read about closures many times here.
But I'm really confusing to know exactly what do closure mean?
A closure is a container for variables, it lets a function access variables from the scope where it was created even when it is called in a different scope.
Example:
function a() {
// a local variable
var x = 42;
function f() {
// use the local variable
return x;
}
// return the function f
return f;
}
// call a to get the inner function
var fx = a();
// call the inner function from out here
var y = fx();
// now y contains the 42 that was grabbed from the variable x inside the function
When the function f
is created, it has a closure with it that contains the variable x
from the scope where it was created. When the function is called from the global scope it can still access the variable x
from the local scope as it is in the closure.
You could simulate the function of the closure by putting variables in an object, and send that along with the function, so that the function can use it later:
function a() {
// a "closure"
var o = { x: 42 };
function f(closure) {
// use the "closure"
return closure.x;
}
// return the "closure" and the function f
return { f: f, o: o };
}
// call a to get the inner function and the "closure"
var fx = a();
// call the inner function with the "closure"
var y = fx.f(fx.o);
// now y contains the 42 that was grabbed from the variable x in the "closure"
Note: The closure contains any identifer in the scope, so in the first example the closure for the function f
also contains the identifier f
which is the function. The function can call itself using the name f
from anywhere, although the identifier f
is local to the function a
.