What are javascript closures?
- December 4th, 2010
- By Ionut
- Write comment
Javascript closures are considered to be advanced stuff, and not many concern about this tehnique. That’s really a shame, because closures are the answer to the problem of how to bind variables to functions that are called at a later time. I actually found the need to use this technique while working on a project.
A closure takes place when a created function binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.
Here is an simple example:
-
function say(name) {
-
var text = name; // variable
-
return function() { alert(text); }
-
}
-
say('Hello')();