Erik W
Erik W

Reputation: 2628

AS3 - Anonymous function 'this'

I have played around with some Anonymous functions, and I noticed that this code does not trace the same thing twice:

public function Main() 
    {
        trace(this);

        stage.addEventListener(MouseEvent.CLICK, function(e:Event):void
        {
            trace(this);
        });
    }

The first trace traces "[object Main]" and the second one traces "[object Global]" (after I clicked). Why does that happen? And what is object Global, is it useful for something?

Upvotes: 0

Views: 174

Answers (2)

helloflash
helloflash

Reputation: 2457

In this case, the keyword this represents the global object, some alternate universe where your function was created, because it was defined outside any custom class or object.

Main class

package 
{
    import flash.display.MovieClip;
    import flash.events.MouseEvent;

    public class Main extends MovieClip
    {
        public function Main()
        {
            // trace(this);
            stage.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void
            {
                trace(this);
            });
        }
    }
}

output

[object global]

In the following example, the function listener toClick is defined as method of the Main class, so this refers to the object Main.

Correct code

package
{
    import flash.display.MovieClip;
    import flash.events.MouseEvent;

    public class Main extends MovieClip
    {
        public function Main()
        {
            // trace(this);
            stage.addEventListener(MouseEvent.CLICK, toClick);
        }

        private function toClick(e:MouseEvent):void
        {
            trace(this); 
        }
    }
}

Output

[object Main]

Upvotes: 2

tziuka
tziuka

Reputation: 545

An anonymous function allows you to create variations to behavior, without having to create a subclass, or some complicate switch statements, so you can now simply assign a function to perform a certain task at runtime. Is like any variable - only this special kind of variable doesn't have a value, but a behavior.

//clasic
bar = function(arg1, arg2, etc) {
    // do something here      
}

when you trace(this) you refere to what function returns and that's a special global 'bar' variable.
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 : http://blogs.adobe.com/simplicity/2007/10/post.html.

Upvotes: 1

Related Questions