User Guide
88 Chapter 3: Using Best Practices
createTextField("label_txt", 100, 0, 20, 100, 22);
label_txt.text = "Circle 1";
someVariable = true;
}
In this code, you attach a movie clip instance from the library and modify its properties using the
with statement. When you do not specify a variable’s scope, you do not always know where you
are setting properties, so your code can be confusing. In the previous code, you might expect
someVariable to be set within the circle1_mc movie clip, but it is actually set in the main
Timeline of the SWF file.
It is easier to follow what is happening in your code if you explicitly specify the variables scope,
instead of relying on the
with statement. The following example shows a slightly longer, but
better, ActionScript example that specifies the variables scope:
this.attachMovie("circle_mc", "circle1_mc", 1);
circle1_mc._x = 20;
circle1_mc._y = Math.round(Math.random()*20);
circle1_mc._alpha = 15;
circle1_mc.createTextField("label_txt", 100, 0, 20, 100, 22);
circle1_mc.label_txt.text = "Circle 1";
circle1_mc.someVariable = true;
There is an exception to this rule. When you are working with the drawing API to draw shapes,
you might have several similar calls to the same methods (such as
lineTo or curveTo) because of
the drawing API’s functionality. For example, when drawing a simple rectangle, you need four
separate calls to the
lineTo method, as the following code shows:
this.createEmptyMovieClip("rectangle_mc", 1);
with (rectangle_mc) {
lineStyle(2, 0x000000, 100);
beginFill(0xFF0000, 100);
moveTo(0, 0);
lineTo(300, 0);
lineTo(300, 200);
lineTo(0, 200);
lineTo(0, 0);
endFill();
}
If you wrote each lineTo or curveTo method with a fully qualified instance name, the code
would quickly become cluttered and difficult to read and debug.
Using variables
For the initial values for variables, assign a default value or allow the value of
undefined, as the
following class example shows. This class sets the initial values of
m_username and m_password to
empty strings:
class User {
private var m_username:String = "";
private var m_password:String = "";
function User(username:String, password:String) {
this.m_username = username;
this.m_password = password;