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?
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.
Closures help in maintaining the state between function calls without using a global variable.
Natively, JavaScript does not support the creation of private variables and methods. A common and practical use of closure is to emulate private variables and methods and allow data privacy. Methods defined within the closure scope are privileged.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With