<?xml version="1.0" encoding="windows-1252"?>
<node id="1018284" title="Re: Real life uses for closures. (update: disambiguation)" created="2013-02-11 22:30:45" updated="2013-02-11 22:30:45">
<type id="11">
note</type>
<author id="708738">
LanX</author>
<data>
<field name="doctext">
What are "delegates"? Talking about C#?&lt;P&gt;&lt;P&gt;

Most things which can be done with closures can be done with OOP and vice versa.&lt;P&gt;&lt;P&gt;


I normally prefer closures because it's light weighted and works in different languages alike.&lt;P&gt;&lt;P&gt;


just a very simple example of [wp://encapsulation].&lt;P&gt;&lt;P&gt;

&lt;c&gt;
{ 
  my $var;

  sub getter { $var };
  sub setter { $var = shift };
}
&lt;/c&gt;&lt;P&gt;&lt;P&gt;


(EDIT: Applied in Perl OO one gets private class-variables in package scope instead of public package variables!)&lt;P&gt;&lt;P&gt;

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.)&lt;P&gt;&lt;P&gt;

TIMTOWTDI.&lt;P&gt;&lt;P&gt;




&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-708738"&gt;
&lt;p&gt;Cheers Rolf
&lt;/div&gt;&lt;/div&gt;&lt;P&gt;&lt;P&gt;

&lt;H5&gt; UPDATE&lt;P&gt;&lt;/H5&gt;&lt;P&gt;

OK people, please lets get the &lt;u&gt;terminology&lt;/u&gt; right:&lt;P&gt;&lt;P&gt;

[wp://Closure_(computer_science)|Closures] are NOT synonymous for &lt;P&gt;&lt;P&gt;

&lt;ul&gt;
&lt;LI&gt; anonymous functions, 
&lt;LI&gt; nor for currying 
&lt;LI&gt; nor do they need to be produced dynamically by a generator function!
&lt;/ul&gt;&lt;P&gt;&lt;P&gt;

Closures are functions which access closed over variables from an (normally restricted) outer scope at definition time.&lt;P&gt;&lt;P&gt;

Look at the example I gave, &lt;C&gt;getter&lt;/C&gt; and &lt;C&gt;setter&lt;/C&gt; are closures, &lt;c&gt;$var&lt;/c&gt; is a closed over lexical variable, and because of the surrounding curlies the variable is only accessible by those closure functions. &lt;P&gt;&lt;P&gt;

No currying, no anonymous functions no dynamic generation!!!&lt;P&gt;&lt;P&gt;

&lt;u&gt;Most of you use them every day!!!&lt;/u&gt;&lt;P&gt;&lt;P&gt;

Whenever you define a file-scoped lexical variable then all functions within this file accessing this variable are closures!</field>
<field name="root_node">
1018281</field>
<field name="parent_node">
1018281</field>
</data>
</node>
