As it happens, like manually created instances, display objects
created programmatically can also be assigned an
instance name via the
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.
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 ...