O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dynamic References to Variables and Methods

Because dynamic instance variable names are often not known until runtime, ActionScript provides a way to specify a variable's name using an arbitrary string expression. The following code shows the general approach:

someObject[someExpression]

In the preceding code, someObject is a reference to the object whose variable is being accessed, and someExpression is any expression that yields a string (indicating that variable's name). The preceding code can be used both to assign a value to a variable and to retrieve a variable's value.

For example, the following code assigns the value "Toronto" to a variable whose name is specified by the literal string expression "city":

var info:Object = new Object();
info["city"] = "Toronto";

The following code assigns the value "Canada" to a variable whose name is specified by the literal string expression "country":

info["country"] = "Canada";

The following code retrieves the value of the variable whose name is specified by the identifier expression, detail:

var detail:String = "city";
trace(info[detail]);  // Displays: Toronto

When ActionScript encounters the code, info[detail], it first determines the value of detail, which is "city," and then looks up the variable named "city" of the object referenced by info.

The syntactic rules for identifiers don't apply to variables created using the [] operator. For example, the following code creates a dynamic instance variable whose name starts with a number:

var info:Object ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required