Debugging in ActionScript 3.0 – Part 2 – Objects Tutorial

26 Jul

Last post I talked about using trace in order to debug variables in Flash. As I mentioned before, trace works great for Strings and Numbers, but not so good for Objects & Arrays. Tracing an Object will return [object Object], which does not tell you much. To see the insides of an Object you can use a for loop. Add the following code to a new actionScript file called ObjectDebug.as:

package ca.flashdev.debug {
  public class ObjectDebug {
    public function traceObject(myObj:Object) {
      trace("Using a regular trace: " + myObj);
      trace("");
      trace("Using a for loop: ");
      for (var i in myObj) {
        trace(i + ' = ' + myObj[i]);
      }
    }
  }
}

Save this file in a folder structure of ca\flashdev\debug.

Create a new movie named traceObject.fla and add the following code to the first frame of the timeline:

import ca.flashdev.debug.ObjectDebug;
var classInstance:ObjectDebug = new ObjectDebug();
var myObj:Object = new Object();
myObj.firstName = "Fraser";
myObj.lastName = "Crosbie";
myObj.occupation = "Flash Developer";
classInstance.traceObject(myObj);

Save this file into the same directory as the ca folder and Test Movie (Ctrl+Enter).
The results in your Output window should be:

Using a regular trace: [object Object]  

Using a for loop:
firstName = Fraser
lastName = Crosbie
occupation = Flash Developer

In AS2 I would recommend using the ObjectDumper to trace the insides of an Object, but it appears that they have yet to write AS3 versions of the mx classes.

Download the source files

3 Responses to “Debugging in ActionScript 3.0 – Part 2 – Objects Tutorial”

  1. AlexS August 27, 2007 at 6:26 pm #

    Fraser, thank you for such a useful stuff on learning AS3.

    I’ve just got confused about this line of code.
    for (var i in myObj) {

    How does it really works? It seems that it repeats action depending on how many variables we have inside the myObj…

    If we want to trace child movieClip objects of the myObj how should we act?

  2. proxykitten July 10, 2009 at 8:57 am #

    Super helpful — was looking for something this simple to trace through what’s tracked in an eventListener. Perfect.

  3. dave0511 March 29, 2010 at 5:01 am #

    Need something recursive for complex objects.

    FYI …AS2.0′s ObjectDumper was horribly flawed in that it didn’t enumerate nameValue pairs at the root level, which of course is the very definition of an associative array, and which are a part of hybrid arrays. ie – trace(ObjectDumper.toString({a:”aVal”,b:123,c:[1,2,"abc"],d:{a1:”bleah”},e:”ack”})) would output nothing – at one point causing me incredible grief thinking my code was faulty when it was actually OjbectDumper.

Leave a Reply