I understand the theoretical concept behind Javascript closures like there is a variable that can only be accessed by inner function and all that...so kind of implementing private variable in JS.
But I wanted to understand some practical examples where Closures are actually helpful. So I need example not to understand what closure is, but practical use cases for Closure.
Two standard examples :
1) keeping variables for callbacks :
var a = [1, 2, 3];
for (var i=0; i<a.length; i++) {
(function(j){
setTimeout(function(){
console.log(a[j]);
}, 1000*j);
})(i);
}
2) keeping variables private
var obj = (function(){
var private = 0;
return {
increment: function(){ private++; },
getValue: function(){ return private; }
}
})();
In fact the simplest is to remember one thing : what is a closure, that is a link from a function to the scope in which it was created. This link prevents the scope (and its variables) to be garbaged and it's the only accessible link to this scope (hence the privacy).
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