I understand what closures are, but I am having some trouble grokking exactly what the term closure
refers to. I have seen the term used in many websites, but rarely do they agree on the actual definition of it.
- Is it the variables that are kept on the stack frame?
- Is it the function that is being returned?
- Is it the scope of the outer function?
- Is it the scope of the inner (returned) function?
- Is it maybe the concept of keeping the variables on the stack-frame after returning the function?
Can someone tell me exactly to what closure
refers to?
Consider the following code that creates a closure with variables a and b
This particular closure can now take any function that operates on the variables a and b
As far as I can tell, a closure is a function defined within another function that outlives the parent function's scope. A common example is callbacks:
In this case, the above
function closure
is defined within the body ofdelay_message
, but the function definition -- as well as the parent function's variablemsg
-- outlive the scope of thedelay_message
function call.For me, the closures in JS allows you to do the following.
"a" remains available in the inner function when added to "b" although it is declared outside.
For an extreme usage of JS closures, you can have a look at the source code of the PURE library (a JS templating engine)
Essentially a closure is a function body closed over its identifiers (variables) within its local environment.
From JavaScript Closures
Two one-sentence summaries:
A very good article on closures
Javascript Closures
A good example over here
JavaScript, time to grok closures
A closure is a function value created from a nested function declaration or function expression (i.e. lambda expression) whose body contains one or more references to variables declared in an outer (but not global) scope.