|Syntactic Confectionery Delight|
Re: Real life uses for closures. (update: disambiguation)by LanX (Chancellor)
|on Feb 12, 2013 at 03:30 UTC||Need Help??|
What are "delegates"? Talking about C#?
Most things which can be done with closures can be done with OOP and vice versa.
I normally prefer closures because it's light weighted and works in different languages alike.
just a very simple example of encapsulation.
(EDIT: Applied in Perl OO one gets private class-variables in package scope instead of public package variables!)
In JS which "only" has prototype-kind of OO, it's possible to simulate many "classical" OO-models just by applying closure extensions. (That is having a "real" class as pattern to construct object instances.)
OK people, please lets get the terminology right:
Closures are NOT synonymous for
Closures are functions which access closed over variables from an (normally restricted) outer scope at definition time.
Look at the example I gave, getter and setter are closures, $var is a closed over lexical variable, and because of the surrounding curlies the variable is only accessible by those closure functions.
No currying, no anonymous functions no dynamic generation!!!
Most of you use them every day!!!
Whenever you define a file-scoped lexical variable then all functions within this file accessing this variable are closures!