ActionScript is a case-sensitive language. This means that variables can have the same name, because slightly different capitalization is considered two separate instances, as the following ActionScript shows:
var firstName:String = "Jimmy"; trace(firstname); //displays: undefined
In earlier versions of Flash (Flash MX and earlier), Flash would trace the string Jimmy in the Output panel. Because Flash is case-sensitive, firstName and firstname are two separate variables. This is an important concept to understand. If your earlier FLA files have slightly varying variable capitalization, you might experience unexpected results or broken functionality when converting the file or application for Flash Player 7.
Note: You should not use two variables that differ only in case. If you are using them as separate variables, change the instance name, not just the case.
Case sensitivity can have a large impact when working with a web service that uses its own rules for variable naming and what case variables are in when they are returned to the SWF file from the server. For example, if you use a Macromedia ColdFusion web service, property names from a structure or object might be all uppercase, such as FIRSTNAME. Unless you use the exact same case in Flash, you are likely to experience unexpected results.
Try to keep ActionScript in a FLA file as generic as possible for the user interface. It is not ideal to write ActionScript that depends on specific target paths. If the code needs to interact with interface elements in a larger application, try using a model-view-controller based approach. For more information, see Using the MVC design pattern.
For more information on guidelines for writing ActionScript, see the following topics:
One of the easiest ways to initialize code using ActionScript 2.0 is to use classes. You can encapsulate all your initialization for an instance within the class's constructor function, or abstract it into a separate method, which you would explicitly call after the variable has been created, as the following code shows:
class Product {
function Product() {
var prod_xml:XML = new XML();
prod_xml.ignoreWhite = true;
prod_xml.onLoad = function(success:Boolean) {
if (success) {
trace("loaded");
} else {
trace("error loading XML");
}
};
prod_xml.load("products.xml");
}
}
The following code could be the first function call in the application, and the only one you make for initialization. Frame 1 of a FLA document that is loading XML might use code that is similar to the following ActionScript:
if (init == undefined) {
var prod_xml:XML = new XML();
prod_xml.ignoreWhite = true;
prod_xml.onLoad = function(success:Boolean) {
if (success) {
trace("loaded");
} else {
trace("error loading XML");
}
};
prod_xml.load("products.xml");
init = true;
}
Use trace statements in your documents to help you debug your code while authoring the FLA file. For example, by using a trace statement and for loop, you can see the values of variables in the Output panel, such as strings, arrays, and objects, as the following example shows:
var day_array:Array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
var numOfDays:Number = day_array.length;
for (var i = 0; i<numOfDays; i++) {
trace(i+": "+day_array[i]);
}
This displays the following information in the Output panel:
0: sun 1: mon 2: tue 3: wed 4: thu 5: fri 6: sat
Using a trace statement is an efficient way to debug your ActionScript.
You can remove your trace statements when you publish a SWF file, which makes minor improvements to playback performance. Before publishing a SWF file, open Publish Settings and select Omit Trace Actions on the Flash tab. For more information on using trace, see trace() in Flash ActionScript Language Reference.
If you refer to a method in the parent class, prefix the method with super so that other developers know from where the method is invoked. The following ActionScript demonstrates the use of proper scoping using the super prefix:
// readable var pelican = super.bird; var animal = super.super.bird;
The following ActionScript is not as readable. Avoid using the following syntax because it does not reveal from where you invoke the method:
// not readable var pelican = bird; // scoped to super.bird var animal = super.super.bird;
One of the more confusing concepts for people learning ActionScript to understand is using the with statement. Consider the following code that uses the with statement:
this.attachMovie("circle_mc", "circle1_mc", 1);
with (circle1_mc) {
_x = 20;
_y = Math.round(Math.random()*20);
_alpha = 15;
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.
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;
}
}
Delete variables or make variables null when you no longer need them. Setting variables to null can still enhance performance. This process is commonly called garbage collection. Deleting variables helps optimize memory use during runtime, because unneeded assets are removed from the SWF file. It is better to delete variables than to set them to null. For more information on performance, see Performance and Flash Player.
For information on naming variables, see Variable names. For more information on deleting objects, see delete in Flash ActionScript Language Reference.
There are several ways to format or write a piece of ActionScript. Differences can exist in the way you form the syntax, such as the way you form it across multiple lines in the Actions panel (for example, where you put brackets ({}) or parentheses [()]).
There are several general guidelines for writing ActionScript syntax. Place one statement per line to increase the readability of your ActionScript. The following example shows correct and incorrect statement usage:
theNum++; //correct theOtherNum++; //correct aNum++; anOtherNum++; //incorrect
There are several ways you can assign variables. Do not embed assignments, which is sometimes used to improve performance in a SWF file at runtime. Despite the performance boost, your code is much harder to read and debug. Consider the following ActionScript example:
var myNum = (a = b + c) + d;
If you assign variables as separate statements, it improves readability, as the following example shows:
var a = b + c; var myNum = a + d;
The following sections describe the preferred ways to format your syntax and statements in ActionScript:
Place conditions put on separate lines in if, else-if, and if-else statements. Your if statements should use braces ({}). You should format braces like the following examples. The if, if-else, and else-if statements have the following formats:
//if statement
if (condition) {
//statements;
}
//if-else statement
if (condition) {
//statements;
} else {
//statements;
}
//else-if statement
if (condition) {
//statements;
} else if (condition) {
//statements;
} else {
//statements;
}
You can write a conditional statement that returns a Boolean value, as the following example shows:
if (cart_array.length>0) {
return true;
} else {
return false;
}
However, compared with the previous code, the ActionScript in the following example is preferable:
return (cart_array.length > 0);
The second snippet is shorter and has fewer expressions to evaluate. It's easier to read and understand.
The following condition checks if the variable y is greater than zero, and returns the result of x/y or a value of 0:
if (y>0) {
return x/y;
} else {
return 0;
}
The following example shows another way to write this code:
return ((y > 0) ? x/y : 0);
The shortened if statement syntax is known as the conditional operator (?:). It lets you convert simple if-else statements into a single line of code. In this case, the shortened syntax reduces readability, and so it is not preferable. Do not use this syntax for complex code, because it is more difficult to spot errors. For more information on using conditional operators, see Writing conditional statements and Writing compound statements.
When you write complex conditions, it is good form to use parentheses [()] to group conditions. If you do not use parentheses, you (or others working with your ActionScript) might run into operator precedence errors.
For example, the following code does not use parentheses around the condition:
if (fruit == apple && veggie == leek) {}
The following code uses good form by adding parentheses around conditions:
if ((fruit == apple) && (veggie == leek)) {}
If you prefer using conditional operators, place the leading condition (before the question mark [?]) inside parentheses. This helps improve the readability of your ActionScript. The following code is an example of ActionScript with improved readability:
(y >= 5) ? y : -y;
Compound statements contain a list of statements within braces ({}). The statements within these braces are indented from the compound statement, as the following ActionScript shows:
if (a == b) {
//this code is indented
trace("a == b");
}
In this example, the opening brace is placed at the end of the compound statement. The closing brace begins a line, and aligns with the beginning of the compound statement.
Place braces around each statement when it is part of a control structure (if-else or for), even if it contains only a single statement. This good practice helps you avoid errors in your ActionScript when you forget to add braces to your code. The following example shows code that is written using poor form:
if (numUsers == 0)
trace("no users found.");
Although this code validates, it is considered poor form because it lacks braces around the statements. In this case, if you add another statement after the trace statement, it is executed regardless of whether the numUsers variable equals 0, which can lead to unexpected results. For this reason, add braces so the code looks like the following example:
if (numUsers == 0) {
trace("no users found");
}
Write the for statement using the following format:
for (init; condition; update) {
// statements;
}
The following structure demonstrates the for statement:
for (var i = 0; i<4; i++) {
myClip_mc.duplicateMovieClip("newClip"+i+"_mc", i+10, {_x:i*100, _y:0});
}
Remember to include a space following each expression in a for statement.
Write while statements, or empty while statements, using one of the following formats:
while (condition) {
//statements;
}
or:
while (condition);
The following ActionScript is an example of a while statement:
var users_ds:mx.data.components.DataSet;
//
users_ds.addItem({name:'Irving', age:34});
users_ds.addItem({name:'Christopher', age:48});
users_ds.addItem({name:'Walter', age:23});
//
users_ds.first();
while (users_ds.hasNext()) {
trace("name:"+users_ds.currentItem['name']+", age:"+users_ds.currentItem['age']);
users_ds.next();
}
Write do-while statements using the following format:
do {
//something
} while (condition);
The following is an example of a do-while statement:
var i:Number = 15;
do {
trace(i);
i++;
} while (i<5);
Do not use parentheses [()]with any return statements that have values. The only time you should use parentheses with return statements is when it makes the value more obvious, which is shown in the third line of the following ActionScript:
return; return myCar.paintColor(); // parentheses used to make the return value obvious return ((paintColor)? paintColor: defaultColor);
All switch statements include a default case. The default case includes a break statement to prevent a fall-through error if another case is added. For example, if the condition in the following example evaluates to A, both the statements for case A and B execute, because case A lacks a break statement. The default case should also be the last case in the switch statement. When a case falls through, it does not have a break statement, but includes a comment in the break statement's place, which you can see in the following example after case A. Write switch statements using the following format:
switch (condition) {
case A :
//statements
//falls through
case B :
//statements
break;
case Z :
//statements
break;
default :
//statements
break;
}
Write try-catch and try-catch-finally statements using the following formats:
//try-catch
try {
//statements
} catch (myError) {
//statements
}
//try-catch-finally
try {
//statements
} catch (myError) {
//statements
} finally {
//statements
}
There are several ways to write listeners for events in Flash MX 2004. Some popular techniques are shown in the following code examples. The first example shows a properly formatted listener syntax, which uses a Loader component to load content into a SWF file. The progress event starts when content loads, and the complete event indicates when loading finishes.
var box_ldr:mx.controls.Loader;
var ldrListener:Object = new Object();
ldrListener.progress = function(evt:Object) {
trace("loader loading:"+Math.round(evt.target.percentLoaded)+"%");
};
ldrListener.complete = function(evt:Object) {
trace("loader complete:"+evt.target._name);
};
box_ldr.addEventListener("progress", ldrListener);
box_ldr.addEventListener("complete", ldrListener);
box_ldr.load("http://www.macromedia.com/images/shared/product_boxes/159x120/159x120_box_flashpro.jpg");
The following example shows another recommended way of using a listener. In this example, you define a function that is called when the user presses a Button component instance on the Stage:
var submit_button:mx.controls.Button;
submit_button.clickHandler = function(evt:Object) {
trace(evt.target._name);
}
By appending Handler to the event name (in this case, click), the event is caught, and you trace an instance name when a user clicks the button.
A slight variation on the first example in this section is to use the handleEvent method, but this technique is slightly more cumbersome. It is not recommended, because you must use a series of if..else statements or a switch statement to detect what event is caught.
var box_ldr:mx.controls.Loader;
var ldrListener:Object = new Object();
ldrListener.handleEvent = function(evt:Object) {
switch (evt.type) {
case 'progress' :
trace("loader loading:"+Math.round(evt.target.percentLoaded)+"%");
break;
case 'complete' :
trace("loader complete:"+evt.target._name);
break;
}
};
box_ldr.addEventListener("progress", ldrListener);
box_ldr.addEventListener("complete", ldrListener);
box_ldr.load("http://www.macromedia.com/images/shared/product_boxes/159x120/159x120_box_flashpro.jpg");
Adding spacing (or white space) to your syntax is recommended because it makes your ActionScript easier to read. The following formatting points are recommended to help promote readability in your ActionScript.
The following example includes a space after a keyword that is followed by parentheses [()]:
do {
//something
} while (condition);
You do not have to put a space between a method name and a following parentheses, as the following example shows:
function checkLogin() {
//statements;
}
checkLogin();
If you follow these guidelines, it is easier to distinguish between method calls and keywords.
In a list of arguments, such as in the following example, include a space after commas:
function addItems(item1:Number, item2:Number):Number {
return (item1+item2);
}
var sum:Number = addItems(1, 3);
Separate all operators and their operands by spaces, as the following ActionScript shows:
var sum:Number = 7 + 3;
An exception to this guideline is the dot (.) operator. Unary operators such as increment (++) and decrement (--) do not have spaces.
RSS feed | Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/mx2004/main_7_2/00000841.html
Comments
Leonard Schreur said on Apr 8, 2005 at 12:29 AM :