
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
ActionScript 2.0 Type Checking Gotchas
|
57
instance in a variable, xmlDoc, then attempts to assign one of its child nodes to a new
variable,
xmlFragment:
var xmlDoc:XML = new XML("<P>Hello world</P>");
var xmlFragment:XML = xmlDoc.firstChild; // Error.
The preceding code causes a type mismatch error because xmlDoc.firstChild is an
XMLNode instance, not an XML instance. To fix the error, we simply declare the
datatype of
xmlFragment as XMLNode instead of XML (change shown in bold):
var xmlDoc:XML = new XML("<P>Hello world</P>");
var xmlFragment:XMLNode = xmlDoc.firstChild; // No error
The preceding code does not cause a type mismatch error because—as we learned
earlier under “Compatible Types”—the compiler knows that every XML instance
has, through inheritance, all the properties and methods of the XMLNode class
(remember that the XML class is a subclass of the XMLNode class despite their
names, which might imply the opposite).
In general, when you want a variable to store an XML instance or any of its children,
you should set the variable’s datatype to XMLNode.
No Type Checking with the [] Operator
When a property or method is accessed via the [] operator, the compiler does not
perform type checking. For example, the following code attempts to execute a non-
existent method. No error occurs ...