How to Iterate The Properties of an AS3 Class

As you may have noticed, you can’t iterate over the properties of an Actionscript 3 class as if they were normal properties of a generic object, unless the class is dynamic of course.

here’s what I mean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package
{
    public class Widget
    {
        public var color:String = "green";
        public var shape:String = "round";
        public var age:String = "5";   
    }
}

var widget:Widget = new Widget();

for(var i:String in widget)
{
    trace(i); // Whaaaaa? Output is blank! 
}

Ok, so as I said.. it doesn’t work. However, there’s trick that you can use! generate an XML list of the class variables, then access them as attributes (using the above example class):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var widget:Widget = new Widget();
var xmlList:XMLList = flash.utils.describeType(widget)..variable;

var vars:Object = new Object();

for (var n:int; n < xmlList.length(); n++)
{  
    vars[xmlList[n]. @ name] = widget[xmlList[n]. @ name];
}

for (var prop:String in vars)
{
    trace(prop); // lists: age, color. shape
}

I took it one step further and pushed the variables into an object called vars so that I could show iterating it as an object.

This came in really handy for me earlier today. Maybe later I’ll elaborate, but I hope that you can see the value in being able to do something like this!

Share on FacebookShare on Google+Share on StumbleUponTweet about this on TwitterEmail this to someone

Facebook comments:

Leave a Reply