Flash IDE / AS3 [object global] Inside of Dynamic Function

I ran across an odd situation inside the Flash IDE where I was trying to trace out parameters about the timeline’s class.

Here’s the code I was running:

import flash.events.*
this.addEventListener(Event.ENTER_FRAME, function(e:Event){trace(this)});

the result looked something like this:

[object global]
[object global]
[object global]

This is a result of the dynamically created function created in the event listener. The function is created in some alternate universe called “global” and has nothing to do with the scope of the stage onto which it is placed. The correct code should be:

import flash.events.*
this.addEventListener(Event.ENTER_FRAME, handleFrame);
function handleFrame(e:Event):void
{
	trace(this);
}

This will produce something like:

[object MyClass]
[object MyClass]
[object MyClass]

4 comments

  1. Both methods creating functions are correct but yes, dynamically created function created in alernate universe called “global”.
    If you want get acces to object, when you create event with “dynamically function” you should use .target with argument event, for instance.
    addEventListener(Event.ADDED_TO_STAGE, function(e:Event) :void {
    trace(e.target.this)
    }
    e.target is a pointer to object when you create eventListener
    So “eventArg.target.this” returns [object MyClass].

  2. Correct
    addEventListener(Event.ADDED_TO_STAGE, function(e:Event) :void {
    trace(e.target.this)
    });

  3. Thank you so much.
    This was the most infuriating problem I had with my new game; I had a timer event calling (parent.parent as Movieclip).someFunction()

    What I ended up doing was proxying the command through another function like this:

    var timer:Timer = new Timer(1 * 1000);
    timer.addEventListener(TimerEvent.TIMER, timerTic);
    timer.start();
    function timerTic(e:TimerEvent):void
    {
    var rolled:int = Math.floor(Math.random() * 100);
    if (rolled <= SHOOT_FREQUENCY)
    {
    shoot();
    }
    }

    public function shoot()
    {
    trace(this + " shot");
    (parent.parent as MovieClip).shoot("Cretin", this);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *