User Guide

98 Chapter 3: Using Best Practices
// Begin loading the XML document.
prod_xml.load(targetXml_string);
}
public function init():Void {
// Display the XML packet.
trace(this.m_products_xml);
}
}
Because you are trying to reference the private member variable within an onLoad handler, the
this keyword actually refers to the prod_xml instance and not the Product class, which you
might expect. For this reason, you must create a pointer to the local class file so that you can
directly reference the class from the
onLoad handler.
Using functions
Reuse blocks of code whenever possible. One way you can reuse code is by calling a function
multiple times, instead of creating different code each time. Functions can be generic pieces of
code, so you can use the same blocks of code for slightly different purposes in a SWF file. Reusing
code lets you create efficient applications and minimize the ActionScript that you must write,
which reduces development time. You can create functions in a class file or write ActionScript
that resides in a code-based component.
If you are using ActionScript 2.0, do not place functions on the Timeline. When using
ActionScript 2.0, place functions into class files whenever possible, as the following example
shows:
class Circle {
public function area(radius:Number):Number {
return (Math.PI*Math.pow(radius, 2));
}
public function perimeter(radius:Number):Number {
return (2 * Math.PI * radius);
}
public function diameter(radius:Number):Number {
return (radius * 2);
}
}
Use the following syntax when you create functions:
function myCircle(radius:Number):Number {
//...
}
Avoid using the following syntax, which is difficult to read:
myCircle = function(radius:Number):Number {
//...
}
The following example puts functions into a class file. This is a best practice when you choose to
use ActionScript 2.0, because it maximizes code reusability. When you want to reuse the
functions in other applications, you can import the existing class rather than rewrite the code
from scratch, or duplicate the functions in the new application.