Am wrapping my head around JavaScript closures and am at a point where things are falling in place; i.e
a closure is the local variables for a function – kept alive after the function has returned, or
a closure is a stack-frame which is not deallocated when the function returns.
Am starting to understand this concept, but the more i understand the more i keep on wondering why do we have to use them.
An example like this one makes me understand the concept but leaves me asking, there is a simpler way of doing this!
function sayHello(name) {
var text = 'Hello ' + name;
var sayAlert = function() { alert(text); }
sayAlert();
}
sayHello('Gath');
Am just wondering why do i have to keep local variable alive? after the function has exited?
Where can i get examples showing of solutions implemented by closure and that nothing else would have worked but closures?
Closures add expressive power to the language. There are some patterns that can be implemented very easily because of closures. A few examples that come to mind include: