Statements are language elements that perform or specify an action at runtime.
For example, the return statement returns a result value for the function in which it executes.
The if statement evaluates a condition to determine the next action that should be taken.
The switch statement creates a branching structure for ActionScript statements.
Attribute keywords alter the meaning of definitions, and can be applied to class, variable, function, and namespace definitions. Definition keywords are used to define entities such as variables, functions, classes, and interfaces. Primary expression keywords represent literal values. For a list of reserved words, see Learning ActionScript 3.0.
Directives include statements and definitions and can have an effect at compile time or runtime. Directives that are neither statements nor definitions are labeled as directives in the following table.
| Statements | |
|---|---|
| break | Appears within a loop (for, for..in, for each..in, do..while, or while) or within a block of statements associated with a particular case within a switch statement. |
| case | Defines a jump target for the switch statement. |
| continue | Jumps past all remaining statements in the innermost loop and starts the next iteration of the loop as if control had passed through to the end of the loop normally. |
| default | Defines the default case for a switch statement. |
| do..while | Similar to a while loop, except that the statements are executed once before the initial evaluation of the condition. |
| else | Specifies the statements to run if the condition in the if statement returns false. |
| for | Evaluates the init (initialize) expression once and then starts a looping sequence. |
| for..in | Iterates over the dynamic properties of an object or elements in an array and executes statement for each property or element. |
| for each..in | Iterates over the items of a collection and executes statement for each item. |
| if | Evaluates a condition to determine the next statement to execute. |
| label | Associates a statement with an identifier that can be referenced by break or continue. |
| return | Causes execution to return immediately to the calling function. |
| super | Invokes the superclass or parent version of a method or constructor. |
| switch | Causes control to transfer to one of several statements, depending on the value of an expression. |
| throw | Generates, or throws, an error that can be handled, or caught, by a catch code block. |
| try..catch..finally | Encloses a block of code in which an error can occur, and then responds to the error. |
| while | Evaluates a condition and if the condition evaluates to true, executes one or more statements before looping back to evaluate the condition again. |
| with | Establishes a default object to be used for the execution of a statement or statements, potentially reducing the amount of code that needs to be written. |
| Attribute Keywords | |
| dynamic | Specifies that instances of a class may possess dynamic properties added at runtime. |
| final | Specifies that a method cannot be overridden or that a class cannot be extended. |
| internal | Specifies that a class, variable, constant or function is available to any caller within the same package. |
| native | Specifies that a function or method is implemented by Flash Player in native code. |
| override | Specifies that a method replaces an inherited method. |
| private | Specifies that a variable, constant, method or namespace is available only to the class that defines it. |
| protected | Specifies that a variable, constant, method, or namespace is available only to the class that defines it and to any subclasses of that class. |
| public | Specifies that a class, variable, constant or method is available to any caller. |
| static | Specifies that a variable, constant, or method belongs to the class, rather than to instances of the class. |
| Definition keywords | |
| ... (rest) parameter | Specifies that a function will accept any number of comma-delimited arguments. |
| const | Specifies a constant, which is a variable that can be assigned a value only once. |
| extends | Defines a class that is a subclass of another class. |
| function | Comprises a set of statements that you define to perform a certain task. |
| get | Defines a getter, which is a method that can be read like a property. |
| implements | Specifies that a class implements one or more interfaces. |
| interface | Defines an interface. |
| namespace | Allows you to control the visibility of definitions. |
| package | Allows you to organize your code into discrete groups that can be imported by other scripts. |
| set | Defines a setter, which is a method that appears in the public interface as a property. |
| var | Specifies a variable. |
| Directives | |
| default xml namespace |
The default xml namespace directive sets the default namespace
to use for XML objects.
|
| import | Makes externally defined classes and packages available to your code. |
| include | Includes the contents of the specified file, as if the commands in the file are part of the calling script. |
| use namespace | Causes the specified namespaces to be added to the set of open namespaces. |
| Namespaces | |
| AS3 | Defines methods and properties of the core ActionScript classes that are fixed properties instead of prototype properties. |
| flash_proxy | Defines methods of the Proxy class. |
| object_proxy | Defines methods of the ObjectProxy class. |
| Primary expression keywords | |
| false | A Boolean value representing false. |
| null | A special value that can be assigned to variables or returned by a function if no data was provided. |
| this | A reference to a method's containing object. |
| true | A Boolean value representing true. |
function functionName(parameter0, parameter1, ...rest){
// statement(s)
}
Specifies that a function will accept any number of comma-delimited arguments. The list of arguments becomes an array that is available throughout the function body. The name of the array is specified after the ... characters in the parameter declaration. The parameter can have any name that is not a reserved word.
If used with other parameters, the ... (rest) parameter declaration must be the last parameter specified. The ... (rest) parameter array is populated only if the number of arguments passed to the function exceeds the number of other parameters.
Each argument in the comma-delimited list of arguments is placed into an element of the array. If you pass an instance of the Array class, the entire array is placed into a single element of the ... (rest) parameter array.
Use of this parameter makes the arguments object unavailable. Although the ... (rest) parameter gives you the same functionality as the arguments array and arguments.length property, it does not provide functionality similar to that provided by arguments.callee. Make sure you do not need to use arguments.callee before using the ... (rest) parameter.
rest:* — An identifier that represents the name of the array of arguments passed in to the function. The parameter does not need to be called rest; it can have any name that is not a keyword. You can specify the data type of the ... (rest) parameter as Array, but this could cause confusion because the parameter accepts a comma-delimited list of values, which is not identical to an instance of the Array class.Example
How to use this example
The following example uses the ... (rest) parameter in two different functions. The first function, traceParams, simply calls the trace() function on each of the arguments in the rest array. The second function, average(), takes the list of arguments and returns the average. The second function also uses a different name, args, for the parameter.
package {
import flash.display.MovieClip;
public class RestParamExample extends MovieClip {
public function RestParamExample() {
traceParams(100, 130, "two"); // 100,130,two
trace(average(4, 7, 13)); // 8
}
}
}
function traceParams(... rest) {
trace(rest);
}
function average(... args) : Number{
var sum:Number = 0;
for (var i:uint = 0; i < args.length; i++) { sum += args[i]; } return (sum / args.length); } Related API Elements
Defines methods and properties of the core ActionScript classes that are fixed properties instead of prototype properties. When you set the "-as3" compiler option to true (which is the default setting in Flex Builder 2), the AS3 namespace is automatically opened for all the core classes. This means that an instance of a core class will use fixed properties and methods instead of the versions of those same properties and methods that are attached to the Object.html">Object class
break [label]
Appears within a loop (for, for..in, for each..in, do..while, or while) or within a block of statements associated with a particular case in a switch statement. When used in a loop, the break statement instructs Flash to skip the rest of the loop body, stop the looping action, and execute the statement following the loop statement. When used in a switch, the break statement instructs Flash to skip the rest of the statements in that case block and jump to the first statement that follows the enclosing switch statement.
In nested loops, break only skips the rest of the immediate loop and does not break out of the entire series of nested loops. To break out of an entire series of nested loops, use label or try..catch..finally.
The break statement can have an optional label that must match an outer labeled statement. Use of a label that does not match the label of an outer statement is a syntax error. Labeled break statements can be used to break out of multiple levels of nested loop statements, switch statements, or block statements. For an example, see the entry for the label statement.
label:* — The name of a label associated with a statement.Example
How to use this example
The following example uses break to exit an otherwise infinite loop:
var i:int = 0;
while (true) {
trace(i);
if (i>= 10) {
break; // this will terminate/exit the loop
}
i++;
}
/*
0
1
2
3
4
5
6
7
8
9
10*/Related API Elements
case jumpTarget: statements
Defines a jump target for the switch statement. If the jumpTarget parameter equals the expression parameter of the switch statement using strict equality (===), Flash Player executes the statements in the statements parameter until it encounters a break statement or the end of the switch statement.
If you use the case statement outside a switch statement, it produces an error and the script doesn't compile.
jumpTarget:* — Any expression.statements:* — Statements to execute if jumpTarget matches the conditional expression in the switch statement.Example
How to use this example
The following example defines jump targets for the switch statement thisMonth. If thisMonth equals the expression in the case statement, the statement executes.
var thisMonth:int = new Date().getMonth();
switch (thisMonth) {
case 0 :
trace("January");
break;
case 1 :
trace("February");
break;
case 5 :
case 6 :
case 7 :
trace("Some summer month");
break;
case 8 :
trace("September");
break;
default :
trace("some other month");
}Related API Elements
[dynamic] [public | internal] [final] class className [ extends superClass ] [ implements interfaceName[, interfaceName... ] ] {
// class definition here
}
Defines a class, which lets you instantiate objects that share methods and properties that you define. For example, if you are developing an invoice-tracking system, you could create an Invoice class that defines all the methods and properties that each invoice should have. You would then use the new Invoice() command to create Invoice objects.
Each ActionScript source file can contain only one class that is visible to other source files or scripts. The externally visible class can be a public or internal class, and must be defined inside a package statement. If you include other classes in the same file, the classes must be placed outside of the package statement and at the end of the file.
The name of the externally visible class must match the name of the ActionScript source file that contains the class. The name of the source file must be the name of the class with the file extension .as appended. For example, if you name a class Student, the file that defines the class must be named Student.as.
You cannot nest class definitions; that is, you cannot define additional classes within a class definition.
You can define a constructor method, which is a method that is executed whenever a new instance of the class is created. The name of the constructor method must match the name of the class. If you do not define a constructor method, a default constructor is created for you.
To indicate that objects can add and access dynamic properties at runtime, precede the class statement with the dynamic keyword. To declare that a class implements an interface, use the implements keyword. To create subclasses of a class, use the extends keyword. (A class can extend only one class, but can implement several interfaces.) You can use implements and extends in a single statement. The following examples show typical uses of the implements and extends keywords:
class C implements Interface_i, Interface_j // OK class C extends Class_d implements Interface_i, Interface_j // OK class C extends Class_d, Class_e // not OK
className:Class — The fully qualified name of the class.Example
How to use this example
The following example creates a class called Plant. The Plant constructor takes two parameters.
// Filename Plant.as
package {
public class Plant {
// Define property names and types
private var _leafType:String;
private var _bloomSeason:String;
// Following line is constructor
// because it has the same name as the class
public function Plant(param_leafType:String, param_bloomSeason:String) {
// Assign passed values to properties when new Plant object is created
_leafType = param_leafType;
_bloomSeason = param_bloomSeason;
}
// Create methods to return property values, because best practice
// recommends against directly referencing a property of a class
public function get leafType():String {
return _leafType;
}
public function get bloomSeason():String {
return _bloomSeason;
}
}
}
var pineTree:Plant = new Plant("Evergreen", "N/A");
// Confirm parameters were passed correctly
trace(pineTree.leafType);
trace(pineTree.bloomSeason); Related API Elements
const identifier = value
Specifies a constant, which is a variable that can be assigned a value only once.
You can strictly type a constant by appending a colon (:) character followed by the data type.
Parametersidentifier:* — An identifier for the constant.Example
How to use this example
The following example shows that an error occurs if you attempt to assign a value to a constant more than once.
const MIN_AGE:int = 21; MIN_AGE = 18; // error
const product_array:Array = new Array("Studio", "Dreamweaver", "Flash", "ColdFusion", "Contribute", "Breeze");
product_array.push("Flex"); // array operations are allowed
product_array = ["Other"]; // assignment is an error
trace(product_array);
Related API Elements
continue [label]
Jumps past all remaining statements in the innermost loop and starts the next iteration of the loop as if control had passed to the end of the loop normally. The continue statement has no effect outside a loop.
In nested loops, use the optional label parameter to skip more than just the innermost loop.
The continue statement can have an optional label that must match an outer labeled statement. Use of a label that does not match the label of an outer statement is a syntax error. Labeled continue statements can be used to skip multiple levels of nested loop statements.
Example
How to use this example
In the following while loop, the continue statement is used to skip the rest of the loop body whenever a multiple of 3 is encountered and jump to the top of the loop, where the condition is tested:
var i:int = 0;
while (i < 10) { if (i % 3 == 0) { i++; continue; } trace(i); i++; }
for (var i:int = 0; i < 10; i++) { if (i % 3 == 0) { continue; } trace(i); }Related API Elements
default: statements
Defines the default case for a switch statement. The statements execute if the expression parameter of the switch statement doesn't equal (using the strict equality [===] operation) any of the expression parameters that follow the case keywords for a given switch statement.
A switch statement does not require a default case statement. A default case statement does not have to be last in the list. If you use a default statement outside a switch statement, it produces an error and the script doesn't compile.
statements:* — Any statements.Example
How to use this example
In the following example, if the day of the week is Saturday or Sunday, none of the case statements apply, so execution moves to the default statement.
var dayOfWeek:int = new Date().getDay();
switch (dayOfWeek) {
case 1 :
trace("Monday");
break;
case 2 :
trace("Tuesday");
break;
case 3 :
trace("Wednesday");
break;
case 4 :
trace("Thursday");
break;
case 5 :
trace("Friday");
break;
default :
trace("Weekend");
}Related API Elements
default xml namespace = ns
The default xml namespace directive sets the default namespace
to use for XML objects.
If you do not set default xml namespace, the default namespace is
the unnamed namespace (with the URI set to an empty string). The scope of a
default xml namespace declaration is within a function block, like
the scope of a variable.
Example
How to use this example
The following example shows that the scope of default xml namespace is a function block:
var nsDefault1:Namespace = new Namespace("http://www.example.com/namespaces/");
default xml namespace = nsDefault1;
var x1:XML = ;
trace("x1 ns: " + x1.namespace());
scopeCheck();
var x2:XML = ;
trace("x2 ns: " + x2.namespace());
function scopeCheck(): void {
var x3:XML = ;
trace("x3 ns: " + x3.namespace());
var nsDefault2:Namespace = new Namespace("http://schemas.xmlsoap.org/soap/envelope/");
default xml namespace = nsDefault2;
var x4:XML = ;
trace("x4 ns: " + x4.namespace());
}
var nsDefault:Namespace = new Namespace("http://www.example.com/namespaces/");
default xml namespace = nsDefault;
var x1:XML = ;
trace(x1.namespace());
// http://www.example.com/namespaces/
var x2:XML = ;
trace(x2.namespace());
// http://www.w3.org/1999/XSL/Transform/
var x3:XML = ;
trace(x3.namespace());
// http://www.example.com/namespaces/
Related API Elements
do { statement(s) } while (condition)Similar to a while loop, except that the statements are executed once before the initial evaluation of the condition. Subsequently, the statements are executed only if the condition evaluates to true.
A do..while loop ensures that the code inside the loop executes at least once. Although you can also do this with a while loop by placing a copy of the statements to be executed before the while loop begins, many programmers believe that do..while loops are easier to read.
If the condition always evaluates to true, the do..while loop is infinite. If you enter an infinite loop, you encounter problems with Flash Player and eventually get a warning message or crash the player. Whenever possible, use a for loop if you know the number of times you want to loop. Although for loops are easy to read and debug, they cannot replace do..while loops in all circumstances.
condition:Boolean — The condition to evaluate. The statement(s) within the do block of code will execute as long as the condition parameter evaluates to true .Example
How to use this example
The following example uses a do..while loop to evaluate whether a condition is true, and traces myVar until myVar is 5 or greater. When myVar is 5 or greater, the loop ends.
var myVar:Number = 0;
do {
trace(myVar);
myVar++;
}
while (myVar < 5); /* 0 1 2 3 4 */Related API Elements
dynamic class className { // class definition here }Specifies that instances of a class may possess dynamic properties added at runtime. If you use the dynamic attribute on a class, you can add properties to instances of that class at runtime. Classes that are not marked as dynamic are considered sealed, which means that properties cannot be added to instances of the class.
If a class is sealed (not dynamic), attempts to get or set properties on class instances result in an error. If you have your compiler set to strict mode and you specify the data type when you create instances, attempts to add properties to sealed objects generate a compiler error; otherwise, a runtime error occurs.
The dynamic attribute is not inherited by subclasses. If you extend a dynamic class, the subclass is dynamic only if you declare the subclass with the dynamic attribute.
Example
How to use this example
The following example creates two classes, one dynamic class named Expando and one sealed class named Sealed, that are used in subsequent examples.
package {
dynamic class Expando {
}
class Sealed {
}
}
var myExpando:Expando = new Expando(); myExpando.prop1 = "new"; trace(myExpando.prop1); // new
var mySealed:Sealed = new Sealed(); mySealed.prop1 = "newer"; // error
Related API Elements
if (condition) {
// statement(s)
}
else {
// statement(s)
}Specifies the statements to run if the condition in the if statement returns false. The curly braces ({}) that enclose the statements to be executed by the else statement are not necessary if only one statement will execute.
condition:Boolean — An expression that evaluates to true or false.Example
How to use this example
In the following example, the else condition is used to check whether the age_txt variable is greater than or less than 18:
if (age_txt.text>=18) {
trace("welcome, user");
}
else {
trace("sorry, junior");
userObject.minor = true;
userObject.accessAllowed = false;
}
if (age_txt.text>18) {
trace("welcome, user");
}
else trace("sorry, junior");
if (score_txt.text>90) {
trace("A");
}
else if (score_txt.text>75) {
trace("B");
}
else if (score_txt.text>60) {
trace("C");
}
else {
trace("F");
}Related API Elements
class className extends otherClassName {}
interface interfaceName extends otherInterfaceName {} Defines a class that is a subclass of another class. The subclass inherits all the methods, properties, functions, and so on that are defined in the superclass. Classes that are marked as final cannot be extended.
You can also use the extends keyword to extend an interface. An interface that extends another interface includes all the original interface's method declarations.
className:Class — The name of the class you are defining.Example
How to use this example
In the following example, the Car class extends the Vehicle class so that all its methods, properties, and functions are inherited. If your script instantiates a Car object, methods from both the Car class and the Vehicle class can be used. The following example shows the contents of a file called Vehicle.as, which defines the Vehicle class:
package {
class Vehicle {
var numDoors:Number;
var color:String;
public function Vehicle(param_numDoors:Number = 2, param_color:String = null) {
numDoors = param_numDoors;
color = param_color;
}
public function start():void {
trace("[Vehicle] start");
}
public function stop():void {
trace("[Vehicle] stop");
}
public function reverse():void {
trace("[Vehicle] reverse");
}
}
}
package {
public class Car extends Vehicle {
var fullSizeSpare:Boolean;
public function Car(param_numDoors:Number, param_color:String, param_fullSizeSpare:Boolean) {
numDoors = param_numDoors;
color = param_color;
fullSizeSpare = param_fullSizeSpare;
}
public function activateCarAlarm():void {
trace("[Car] activateCarAlarm");
}
public override function stop():void {
trace("[Car] stop with antilock brakes");
}
}
}var myNewCar:Car = new Car(2, "Red", true); myNewCar.start(); // [Vehicle] start myNewCar.stop(); // [Car] stop with anti-lock brakes myNewCar.activateCarAlarm(); // [Car] activateCarAlarm
package {
class Truck extends Vehicle {
var numWheels:Number;
public function Truck(param_numDoors:Number, param_color:String, param_numWheels:Number) {
super(param_numDoors, param_color);
numWheels = param_numWheels;
}
public override function reverse():void {
beep();
super.reverse();
}
public function beep():void {
trace("[Truck] make beeping sound");
}
}
}var myTruck:Truck = new Truck(2, "White", 18); myTruck.reverse(); // [Truck] make beeping sound [Vehicle] reverse myTruck.stop(); // [Vehicle] stop
Related API Elements
false
A Boolean value representing false. A Boolean value is either true or false; the opposite of false is true.
When automatic data typing converts false to a number, it becomes 0; when it converts false to a string, it becomes "false".
Note: The string "false" converts to the Boolean value true.
Example
How to use this example
This example shows how automatic data typing converts false to a number and to a string:
var bool1:Boolean = Boolean(false);
// converts it to the number 0
trace(1 + bool1); // outputs 1
// converts it to a string
trace("String: " + bool1); // outputs String: false
trace(Boolean("false")); // true
if ("false") {
trace("condition expression evaluated to true");
}
else {
trace("condition expression evaluated to false");
}
// condition expression evaluated to true
Related API Elements
final function methodName() {
// your statements here
}
final class className {} Specifies that a method cannot be overridden or that a class cannot be extended. An attempt to override a method, or extend a class, marked as final results in an error.
methodName:Function — The name of the method that cannot be overridden.className:Class — The name of the class that cannot be extended.Related API Elements
Defines methods of the Proxy class. The Proxy class methods are in their own namespace to avoid name conflicts in situations where your Proxy subclass contains instance method names that match any of the Proxy class method names.
ParametersRelated API Elements
for ([init]; [condition]; [next]) {
// statement(s)
}
Evaluates the init (initialize) expression once and then starts a looping sequence. The looping sequence begins by evaluating the condition expression. If the condition expression evaluates to true, statement is executed and next is evaluated. The looping sequence then begins again with the evaluation of the condition expression.
The curly braces ({}) that enclose the block of statements to be executed by the for statement are not necessary if only one statement will execute.
init — An optional expression to evaluate before beginning the looping sequence; usually an assignment expression. A var statement is also permitted for this parameter.condition — An optional expression to evaluate before beginning the looping sequence; usually a comparison expression. If the expression evaluates to true, the statements associated with the for statement are executed.next — An optional expression to evaluate after the looping sequence; usually an increment or decrement expression.Example
How to use this example
The following example uses for to add the elements in an array:
var my_array:Array = new Array();
for (var i:Number = 0; i < 10; i++) { my_array[i] = (i + 5) * 10; } trace(my_array); // 50,60,70,80,90,100,110,120,130,140 var sum:Number = 0;
for (var i:Number = 1; i <= 100; i++) { sum += i; } trace(sum); // 5050var sum:Number = 0; for (var i:Number = 1; i <= 100; i++) sum += i; trace(sum); // 5050
Related API Elements
for (variableIterant:String in object){
// statement(s)
} Iterates over the dynamic properties of an object or elements in an array and executes statement for each property or element. Object properties are not kept in any particular order, so properties may appear in a seemingly random order.
Fixed properties, such as variables and methods defined in a class, are not enumerated by the for..in statement.
To get a list of fixed properties, use the describeType() function, which is in the flash.utils package.
variableIterant:String — The name of a variable to act as the iterant, referencing each property of an object or element in an array.Example
How to use this example
The following example uses for..in to iterate over the properties of an object:
var myObject:Object = {firstName:"Tara", age:27, city:"San Francisco"};
for (var prop in myObject) {
trace("myObject."+prop+" = "+myObject[prop]);
}
/*
myObject.firstName = Tara
myObject.age = 27
myObject.city = San Francisco
*/
var myObject:Object = {firstName:"Tara", age:27, city:"San Francisco"};
for (var name in myObject) {
if (typeof (myObject[name]) == "string") {
trace("I have a string property named "+name);
}
}
/*
I have a string property named city
I have a string property named firstName
*/
More examples
Related API Elements
for each (variableIterant in object){
// statement(s)
} Iterates over the items of a collection and executes statement for each item. Introduced as a part of the E4X language extensions, the for each..in statement can be used not only for XML objects, but also for objects and arrays.
The for each..in statement iterates only through the dynamic properties of an object, not the fixed properties. A fixed property is a property that is defined as part of a class definition. To use the for each..in statement with an instance of a user-defined class, you must declare the class with the dynamic attribute.
Unlike the for..in statement, the for each..in statement iterates over the values of an object's properties, rather than the property names.
variableIterant:* — The name of a variable to act as the iterant, referencing the item in a collection.object:Object — The name of a collection over which to iterate. The collection can be an XML object, a generic object, or an array.Example
How to use this example
The following example uses for each..in to iterate over the values held by the properties of an object:
var myObject:Object = {firstName:"Tara", age:27, city:"San Francisco"};
for each (var item in myObject) {
trace(item);
}
/*
Tara
27
San Francisco
*/
var myArray:Array = new Array("one", "two", "three");
for each(var item in myArray)
trace(item);
/*
one
two
three
*/
var myObject:Object = {firstName:"Tara", age:27, city:"San Francisco"};
for each (var item in myObject) {
if (item is String) {
trace("I have a string property with value " + item);
}
}
/*
I have a string property with value Tara
I have a string property with value San Francisco
*/
var doc:XML =Hello
Hola
Bonjour
More examples