I came across them, but I have yet to see why I should use them. Could someone explain it?
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.
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.
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