Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use for anonymous functions in AS3?

I came across them, but I have yet to see why I should use them. Could someone explain it?

like image 361
MKII Avatar asked Feb 16 '12 10:02

MKII


2 Answers

It is comfortably to use in closures, when you need not name for this function. I. e. this way:

var myFunc : Function = function() : void {trace("Hello world!");}
doSomething(myFunc);

or this:

button.addEventListener(MouseEvent.CLICK,
    function(e : MouseEvent) : void
    {
        // doSomething
    });

You do not have to use them, but you may if it is easier.

like image 109
Sat Avatar answered Oct 29 '22 08:10

Sat


Essentially, an anonymous function allows you to create very fine-grained variations to behavior, without having to create a subclass, or to encapsulate what would otherwise have to be a complex switch statement into a short, clean method block: Where you would have to make a lot of decisions based on state, you can now simply assign a function to perform a certain task at runtime. Think of it like any variable - only this special kind of variable doesn't have a value, but a behavior.

The standard example for this is event listeners, but you can also apply this to any other functionality you desire.

You can find out about anonymous functions here, and subsequently learn about the concept of closures at Wikipedia. Admittedly, the Wikipedia source is a bit heavy with technical terms, but Martin Fowler also has a quite readable blog post on this topic.

like image 38
weltraumpirat Avatar answered Oct 29 '22 06:10

weltraumpirat