A closure is a function object that has a reference to the variables in the context it was created in.
var increment = (function () {
var i = 0;
return function () {
return ++i;
}
}());
Within the IIFE we have set i
to 0
. increment
is initialised the returned function that performs the increment. Anytime increment is called, the variable i
(which was created in the context of the anonymous function) is incremented and returned.
Us Northerners say "never forget where you came from", and it's true.