Closures
A closure is bascially an inner function made accessible from outside of its parent function with in-scope variables and their values incorporated from the environment in which it was created.
In that environment, it has access to its own local variables, to its outer function's variables and the global variables (declared outside its outer function).
To begin with, we declare a function called
f() containing a variable
pi, and an inner function called
getPi(), which returns the value of the
variable pi. The function
f() returns the function
getPi()
without executing it (opening and closing parentheses
are not there).
function f() {
var pi = 3.141;
function getPi() {
return pi;
}
return getPi;
}
The variable pi and the inner function
getPi() are both local to the function
f(), and neither is accessible outside of
f(). Trying to access them directly will
result in ReferenceError being thrown into
the browser's console.
getPi() however can access variables
declared in its parent function f(), and
hence can also access pi.
Now we can call the function f() and
assign it to a variable, say, p
var p = f();
f() returns its inner function
getPi() and stores it in
p, without executing it.
p now has access to the local variables
and functions of f(), which are supposed
to be private to f(). On calling
p()
p();
f()'s inner function
getPi() gets called, and returns the
assigned value of pi, which is
f()'s local variable.
p() now has become a
closure.