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

Instance Names for Programmatically Created Display Objects

As it happens, like manually created instances, display objects created programmatically can also be assigned an instance name via the name variable. For example, the following code creates a TextField instance, gives it the instance name "price," adds it to a container, and then retrieves a reference to it by name.

var t:TextField = new TextField();
t.text = "$99.99";
t.name = "price"
var detailsPage:Sprite = new Sprite();
detailsPage.addChild(t);
trace(detailsPage.getChildByName("price"));  // Displays: [object TextField]

The preceding code may appear convenient because it offers a way to access an object on the display list according to some programmer-determined label, rather than by object reference or depth position. However, using instance names in this way is prone to error because ActionScript does not require instance names to be unique and does not throw an exception for attempts to access nonexistent instance names. Hence, use of instance names with programmatically created display objects should be avoided.

Tip

Instance names should typically be used only when referring to text field instances or instances of Library symbols created manually in the Flash authoring tool.

Programmatically created display objects should always be accessed by reference. For example, the following code shows two versions of displayPrice( ), a hypothetical method that displays the price of a product. Both of the following versions of the ...

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