Well, I recently learned about closures in Javascript.
While i find it's concept truly amazing, i have yet to find a good application for them, myself.
In all the blog posts, all the tuturials i found, i got a good explanation of what they are and how to work with them.
What i can't find anywhere are examples that make me think: "Wow! you can do THIS with closures? Awesome!!!". All the examples i find are purely academic like this one.
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
var sayNumber = say667();
alert(sayNumber());
So, i was wondering if any of you can share some mind-blowing experiences with these special kind of functions.
I know that this is sort of an open question, but i will attribute the answer to whoever makes me WOW the most.
Thanks
Closures are used all the time with callback functions that are called some time later because they allow you to access the local variables of the host calling function or can be used to "freeze" values of local variables into private variables for a particular callback when the local variable itself will be changing to another value as the code continues to execute, but before the callback is called.
Here are examples of closures in answers I've supplied here on SO.
Access parent local variables from setTimeout callback: https://stackoverflow.com/a/7032671/816620
Pass non-static information into a delayed callback: https://stackoverflow.com/a/8660518/816620
I know I've used closures dozens of times in the last month just here in SO answers (I'm just not sure how to quickly find more examples with search without wading through lots of posts).
And, here's a useful closure that creates a private variable:
function slides(images) {
var slideImages = images || [];
// because of this closure, the variable slideImages is available
// to the method defined in here even though the slides function
// has already finished executing
this.addSlide = function(url) {
slideImages.push(url);
}
this.clearSlides = function() {
slideImages = [];
}
}
// the slideImages variable is not available out here
// it is truly private inside the clsoure
var slideshow = new slides(imgArray);
slideshow.addSlide("xxx.jpeg");
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