Accessing Fields of an Object by Name (AS3)

Started by zourtney, Oct 16, 2008, 09:58 AM

Previous topic - Next topic

zourtney

Here's an old trick: accessing object properties by a string representation of their name.

I came across an instance where I wanted to format the output of a class dynamically. I wanted to pass in which properties of the class to display. Instead of making a special case for each known field of the class, I used the magic of dynamic objects.

private var obj:Object = {name: "Bob", age:24, height:68};   // any object or class

private function formattedTrace( fields:Array ):void
{
// loop through all fields in the array
for each ( var str:String in fields )
{
// trace out the field name and the value
trace( str + ": " + obj[str] );
}
}


Note that in my actual application of this code, "obj" was a class with regular getters and setters. This function is easy enough to call.


private var fields:Array = ["name", "age"];   // the names of the fields on "obj" you want to display
formattedTrace( fields );


This is almost definitely slower than if we did something explicit, listing out all known fields. Plus, it makes run time errors really, REALLY easy to create (ie, throwing "Football" in the fields array). However, it is flexible and viable for debugging purposes at least.