views:

1029

answers:

3

Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.

I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.

Are there any catches of using them? Do they work pretty much the same way as in C#.

I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!

private function showPanel(index:int):void { 

_timer = new Timer(1000, 1);  
_timer.addEventListener(TimerEvent.TIMER, function(event:Event):void 
{
 //  show the next panel
 showPanel(index++);
});
+1  A: 

The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.

But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.

Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).

Hope this helps.

Mitch Haile
A: 

I found what originally made me NOT want to do this, but I had forgotten the details:

http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539

(This is what Mitch mentioned - as far as the 'this' keyword being out of scope)

So thats Adobe's answer, however I am much more likely to need to refer to local variables than 'this'.

How do others interpret Adobe's recommendation ?

Simon
+1  A: 

One additional problem is that garbage collection is broken when it comes to closures (at least in Flash 9). The first instance of a given closure (from a lexical standpoint) will never be garbage collected - along with anything else referenced by the closure in the scope chain.