|
|
|
|
|
by ajuc
4048 days ago
|
|
Closure is a function that "remembers" all variables that were in scope at the place where that function was created. It can then use these variables (as if they were global variables), even if they are outside of the scope when the function is invoked. These variables also won't get garbage collected because of that. This feature is most useful when you create anonymous functions that you pass around. Example: function foo() {
var localVariable = 3;
return (function () { // this anonymous function can reference localVariable because it is a closure and remembers outside scope
localVariable++;
alert(localVariable);
})
}
var increase = foo(); //foo returns freshly created anonymous function that we assign to local variable "increase".
//foo also created local variable "localVariable"
//and it went out of scope when foo returned,
//but that variable won't be GC-ed as long we keep reference to "increase",
//because increase has that "localVariable" in scope
increase() // we call that variable - it executes that functions and writes 4
function bar() {
var localVariable = 100; //this is different variable with the same name
increase(); //bar can reference increase because bar is a closure, so it remembers outside scope
}
bar(); // writes 5
increase(); //writes 6
var increase2 = foo(); // this creates another function and another localVariable
increase2(); //writes 4
increase(); //writes 7
It's useful for similar things as objects in OO programming (grouping data with code), but encourages different approach to this.Closures also make functional code with passing functions bearable - without it you would have to explicitly pass variables from scope to each function, or to depend on dynamic scope, so your functions would use different variables depending where they are called. |
|
I should probably be more precise - only the variables from outside scope that the closure actually uses won't get GCed as long as that closure is referenced. Other variables will.