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. | |
class | Defines a class, which lets you instantiate objects that share methods and properties that you define. | |
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. |
... (rest) parameter | Definition keywords |
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
AS3 | Namespaces |
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 class's prototype object. The use of fixed properties usually provides better performance, but at the cost of backward compatibility with the ECMAScript edition 3 language specification (ECMA-262).
Related API Elements
break | Statements |
|
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 | Statements |
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
class | Definition keywords |
[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 | Definition keywords |
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 | Statements |
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 |
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 | Directives |
|
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..while | Statements |
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 | Attribute Keywords |
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
else | Statements |
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
extends | Definition keywords |
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 | Primary expression keywords |
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 | Attribute Keywords |
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
flash_proxy | Namespaces |
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 | Statements |
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); // 5050
var sum:Number = 0; for (var i:Number = 1; i <= 100; i++) sum += i; trace(sum); // 5050
Related API Elements
for..in | Statements |
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..in | Statements |
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
; for each (var item in doc.p) { trace(item); } /* Hello Hola Bonjour */
More examples
function | Definition keywords |
function functionName([parameter0, parameter1,...parameterN]) : returnType{ // statement(s) } var functionName:Function = function ([parameter0, parameter1,...parameterN]) : returnType{ // statement(s) } |
Comprises a set of statements that you define to perform a certain task. You can define a function in one location and invoke, or call, it from different scripts in a SWF file. When you define a function, you can also specify parameters for the function. Parameters are placeholders for values on which the function operates. You can pass different parameters to a function each time you call it so you can reuse the function in different situations.
Use the return
statement in a function's statement(s)
block to cause a function to generate, or return, a value.
Usage 1: You can use the function
keyword to define a function with the specified function name, parameters, and statements. When a script calls a function, the statements in the function's definition are executed. Forward referencing is permitted; within the same script, a function may be declared after it is called. A function definition replaces any prior definition of the same function. You can use this syntax wherever a statement is permitted.
Usage 2: You can also use function
to create an anonymous function and return a reference to it. This syntax is used in expressions and is particularly useful for installing methods in objects.
For additional functionality, you can use the arguments
object in your function definition. The arguments
object is commonly used to create a function that accepts a variable number of parameters and to create a recursive anonymous function.
functionName:Function — The name of the new function. | |
returnType:* — The data type of the return value. |
Example
How to use this example
The following example defines the function sqr, which returns the value of a number squared:
function sqr(xNum:Number) { return Math.pow(xNum, 2); } var yNum:Number = sqr(3); trace(yNum); // 9
var yNum:Number = sqr(3); trace(yNum); // 9 function sqr(xNum:Number) { return Math.pow(xNum, 2); }
Related API Elements
get | Definition keywords |
function get property() : returnType{ // your statements here } |
Defines a getter, which is a method that can be read like a property.
A getter is a special function that returns the value of a property declared with the var
or const
keyword.
Unlike other methods, a getter is called without parentheses (()
), which makes the getter appear to be a variable.
Getters allow you to apply the principle of information hiding by letting you create a public interface for a private property. The advantage of information hiding is that the public interface remains the same even if the underlying implementation of the private property changes.
Another advantage of getters is that they can be overridden in subclasses, whereas properties declared with var
or const
cannot.
A getter can be combined with a setter to create a read-write property. To create a read-only property, create a getter without a corresponding setter. To create a write-only property, create a setter without a corresponding getter.
Parametersproperty:* — The identifier for the property that get accesses; this value must be the same as the value used in the corresponding set command. | |
returnType:* — The data type of the return value. |
Example
How to use this example
The following example defines a Team class. The Team class includes getter and setter methods that let you retrieve and set properties within the class:
package { public class Team { var teamName:String; var teamCode:String; var teamPlayers:Array = new Array(); public function Team(param_name:String, param_code:String) { teamName = param_name; teamCode = param_code; } public function get name():String { return teamName; } public function set name(param_name:String):void { teamName = param_name; } } }
var giants:Team = new Team("San Fran", "SFO"); trace(giants.name); giants.name = "San Francisco"; trace(giants.name); /* San Fran San Francisco */
Related API Elements
if | Statements |
if (condition) { // statement(s) } |
Evaluates a condition to determine the next statement to execute. If the condition is
true
, Flash Player runs the statements that follow the condition inside curly braces ({}
). If the condition is false
, Flash Player skips the statements inside the curly braces and runs the statements following the curly braces. Use the if
statement along with the else
statement to create branching logic in your scripts.
The curly braces ({}
) that enclose the statements to be executed by the if
statement are not necessary if only one statement will execute.
condition:Boolean — An expression that evaluates to true or false. |
Related API Elements
implements | Definition keywords |
myClass implements interface01 [, interface02 , ...] |
Specifies that a class implements one or more interfaces. When a class implements an interface, the class must define all the methods declared in the interface.
Any instance of a class that implements an interface is considered a member of the data type defined by the interface. As a result, the is
operator returns true
when the class instance is the first operand and the interface is the second; in addition, type coercions to and from the data type defined by the interface work.
Related API Elements
import | Directives |
import packageName.className import packageName.* |
Makes externally defined classes and packages available to your code.
For example, if you want to use the flash.display.Sprite class in a script, you must import it.
This requirement is different from previous versions of ActionScript, in which the import
directive was optional.
After using the import
directive, you can use the full class name,
which includes the package name, or just the name of the class.
import flash.display.Sprite; // name of class only var mySprite:Sprite = new Sprite(); // full class name var mySprite:flash.display.Sprite = new flash.display.Sprite();
If there are several classes in the package that you want to access, you can import them all in a single statement, as shown in the following example:
import flash.display.*;
The import
directive imports only the classes, functions, and variables that reside at the top level of the imported package. Nested packages must be explicitly imported.
If you import a class but do not use it in your script, the class is not exported as part of the SWF file. This means you can import large packages without being concerned about the size of the SWF file; the bytecode associated with a class is included in a SWF file only if that class is actually used. One disadvantage of importing classes that you do not need is that you increase the likelihood of name collisions.
// On Frame 1 of a FLA: import adobe.example.*; var myFoo:foo = new foo();Parameters
packageName:* — The name of a package you have defined in a separate class file. | |
className:Class — The name of a class you have defined in a separate class file. |
include | Directives |
include "[path]filename.as" |
Includes the contents of the specified file, as if the commands in the file are part of the calling script.
The include
directive is invoked at compile time. Therefore, if you make any changes to an included file, you must save the file and recompile any SWF files that use it.
interface | Definition keywords |
interface InterfaceName [extends InterfaceName ] {} |
Defines an interface. Interfaces are data types that define a set of methods; the methods must be defined by any class that implements the interface.
An interface is similar to a class, with the following important differences:
- Interfaces contain only declarations of methods, not their implementation. That is, every class that implements an interface must provide an implementation for each method declared in the interface.
- Interface method definitions cannot have any attribute such as
public
orprivate
, but implemented methods must be marked aspublic
in the definition of the class that implements the interface. - Multiple interfaces can be inherited by an interface by means of the
extends
statement, or by a class through theimplements
statement.
Unlike ActionScript 2.0, ActionScript 3.0 allows the use of getter and setter methods in interface definitions.
ParametersRelated API Elements
internal | Attribute Keywords |
[internal] var varName [internal] const kName [internal] function functionName() { // your statements here } [internal] class className{ // your statements here } [internal] namespace nsName |
Specifies that a class, variable, constant, or function is available to any caller within the same package. Classes, properties, and methods belong to the internal
namespace by default.
className:Class — The name of the class that you want to specify as internal. | |
varName:* — The name of the variable that you want to specify as internal. You can apply the internal attribute whether the variable is part of a class or not. | |
kName:* — The name of the constant that you want to specify as internal. You can apply the internal attribute whether the constant is part of a class or not. | |
functionName:Function — The name of the function or method that you want to specify as internal. You can apply the internal attribute whether the function is part of a class or not. | |
nsName:Namespace — The name of the namespace that you want to specify as internal. You can apply the internal attribute whether the namespace is part of a class or not. |
Related API Elements
label | Statements |
label: statement label: { statements } |
Associates a statement with an identifier that can be referenced by break
or continue
.
In nested loops, a break
or continue
statement
that does not reference a label can skip only the rest of the immediate
loop and does not skip the entire series of loops.
However, if the statement that defines the entire series of loops has an
associated label, a break
or continue
statement
can skip the entire series of loops by referring to that label.
Labels also allow you to break out of a block statement. You cannot
place a break
statement that does not reference a label
inside a block statement unless the block statement is part of a loop.
If the block statement has an associated label, you can place a
break
statement that refers to that label inside the block statement.
label:* — A valid identifier to associate with a statement. | |
statements:* — Statement to associate with the label. |
Example
How to use this example
The following example shows how to use a label with a nested loop to break out of the entire series of loops. The code uses a nested loop to generate a list of numbers from 0 to 99. The break statement occurs just before the count reaches 80. If the break statement did not use the outerLoop label, the code would skip only the rest of the immediate loop and the code would continue to output the numbers from 90 to 99. However, because the outerLoop label is used, the break statement skips the rest of the entire series of loops and the last number output is 79.
outerLoop: for (var i:int = 0; i < 10; i++) { for (var j:int = 0; j < 10; j++) { if ( (i == 8) && (j == 0)) { break outerLoop; } trace(10 * i + j); } } /* 1 2 ... 79 */
foo: { trace("a"); break foo; trace("b"); } // a
Related API Elements
namespace | Definition keywords |
namespace name [= uri] |
Allows you to control the visibility of definitions. Predefined namespaces include public
, private
, protected
, and internal
.
The following steps show how to create, apply, and reference a namespace:
- First, define the custom namespace using the
namespace
keyword. For example, the codenamespace version1
creates a namespace calledversion1
. - Second, apply the namespace to a property or method by using your custom namespace in the property or method declaration. For example, the code
version1 myProperty:String
creates a property namedmyProperty
that belongs to theversion1
namespace - Third, reference the namespace by using the
use
keyword or by prefixing an identifier with the namespace. For example, the codeuse namespace version1;
references theversion1
namespace for subsequent lines of code, and the codeversion1::myProperty
references theversion1
namespace for themyProperty
property.
name:Namespace — The name of the namespace, which can be any legal identifier. | |
uri:String — The Uniform Resource Identifier (URI) of the namespace. This is an optional parameter. |
Related API Elements
native | Attribute Keywords |
native function functionName(); class className { native function methodName(); } |
Specifies that a function or method is implemented by Flash Player in native code. Flash Player uses the native
keyword internally to declare functions and methods in the ActionScript application programming interface (API). This keyword cannot be used in your own code.
null | Primary expression keywords |
null |
A special value that can be assigned to variables or returned by a function if no data was provided. You can use null
to represent values that are missing or that do not have a defined data type.
The value null
should not be confused with the special value undefined
. When null
and undefined
are compared with the equality (==
) operator, they compare as equal. However, when null
and undefined
are compared with the strict equality (===
) operator, they compare as not equal.
Example
How to use this example
The following example checks the first six values of an indexed array and outputs a message if no value is set (if the value == null):
var testArray:Array = new Array(); testArray[0] = "fee"; testArray[1] = "fi"; testArray[4] = "foo"; for (i = 0; i < 6; i++) { if (testArray[i] == null) { trace("testArray[" + i + "] == null"); } } /* testArray[2] == null testArray[3] == null testArray[5] == null */
Related API Elements
object_proxy | Namespaces |
Defines methods of the ObjectProxy class. The ObjectProxy class methods are in their own namespace to avoid name conflicts in situations where a Proxy subclass contains instance method names that match any of the Proxy class method names.
Parametersoverride | Attribute Keywords |
override function name() { // your statements here } |
Specifies that a method replaces an inherited method. To override an inherited method, you must use the override
attribute and ensure that the name, class property attribute, number and type of parameters, and the return type match exactly. It is an error to attempt to override a method without using the override
attribute. Likewise, it is an error to use the override
attribute if the method does not have a matching inherited method.
You cannot use the override
attribute on any of the following:
- Variables
- Constants
- Static methods
- Methods that are not inherited
- Methods that implement an interface method
- Inherited methods that are marked as
final
in the superclass
Although you cannot override a property declared with var
or const
, you can achieve similar functionality by making the base class property a getter-setter and overriding the methods defined with get
and set
.
name:Function — The name of the method to override. |
Related API Elements
package | Definition keywords |
package packageName { class someClassName { } } |
Allows you to organize your code into discrete groups that can be imported by other scripts. You must use the package
keyword to indicate that a class is a member of a package.
packageName:* — The name of the package. |
Related API Elements
private | Attribute Keywords |
class className{ private var varName; private const kName; private function methodName() { // your statements here } private namespace nsName; } |
Specifies that a variable, constant, or method is available only to the class that declares or defines it. Unlike in ActionScript 2.0, in ActionScript 3.0 private
no longer provides access to subclasses. Moreover, private
restricts access at both compile time and runtime. By default, a variable or function is available to any caller in the same package. Use this keyword if you want to restrict access to a variable or function.
You can use this keyword only in class definitions, not in interface definitions. You cannot apply private
to a class or to any other package-level definitions.
varName:* — The name of the variable that you want to specify as private. You can apply the private attribute only if the variable is inside a class. | |
kName:* — The name of the constant that you want to specify as private. You can apply the private attribute only if the constant is inside a class. | |
methodName:Function — The name of the method that you want to specify as private. You can apply the private attribute only if the method is inside a class. | |
nsName:Namespace — The name of the namespace that you want to specify as private. You can apply the private attribute only if the namespace is inside a class. |
Example
How to use this example
The following example demonstrates how you can hide certain properties within a class using the private keyword.
class A { private var alpha:String = "visible only inside class A"; public var beta:String = "visible everywhere"; } class B extends A { function B() { alpha = "Access attempt from subclass"; // error } }
Related API Elements
protected | Attribute Keywords |
class className{ protected var varName; protected const kName; protected function methodName() { // your statements here } protected namespace nsName; } |
Specifies that a variable, constant, method, or namespace is available only to the class that defines it and to any subclasses of that class. The definition of protected
in ActionScript 3.0 is similar to the definition of the ActionScript 2.0 version of private
, except that protected
restricts access at both compile time and runtime. By default, a variable or function is available to any caller within the same package. Use this keyword if you want to restrict access to a variable or function.
You can use this keyword only in class definitions, not in interface definitions. You cannot apply private
to a class, or to any other package-level definitions.
The definition of protected
in ActionScript 3.0 is more restrictive than that of protected
in the Java programming language. In ActionScript 3.0 protected
limits access strictly to subclasses, whereas in Java protected
also allows access to any class in the same package. For example, if a class named Base
contains a property marked as protected
, in ActionScript 3.0 only classes that extend Base can access the protected property. In Java, any class in the same package as Base has access to the protected property even if the class is not a subclass of Base.
varName:* — The name of the variable that you want to specify as protected. You can apply the protected attribute only if the variable is inside a class. | |
kName:* — The name of the constant that you want to specify as protected. You can apply the protected attribute only if the constant is inside a class. | |
methodName:Function — The name of the method that you want to specify as protected. You can apply the protected attribute only if the method is inside a class. | |
nsName:Namespace — The name of the namespace that you want to specify as protected. You can apply the protected attribute only if the namespace is inside a class. |
Example
How to use this example
The following example creates a protected class variable in class A, and successfully accesses that variable in class B because class B is a subclass of class A.
class A { private var alpha:String = "visible only inside class A"; protected var beta:String = "visible inside class A and its subclasses"; } class B extends A { public function B() { beta = "Access attempt from subclass succeeded"; trace(beta); // Access attempt from subclass succeeded } }
Related API Elements
public | Attribute Keywords |
public var varName public const kName public function functionName() { // your statements here } public class className { // your statements here } public namespace nsName |
Specifies that a class, variable, constant, or method is available to any caller. Classes, variables, and methods are internal by default, which means that they are visible only within the current package. To make a class, variable, or method visible to all callers, you must use the public
attribute.
className:Class — The name of the class that you want to specify as public. | |
varName:* — The name of the variable that you want to specify as public. You can apply the public attribute whether the variable is part of a class or not. | |
kName:* — The name of the constant that you want to specify as public. You can apply the public attribute whether the constant is part of a class or not. | |
functionName:Function — The name of the function or method that you want to specify as public. You can apply the public attribute whether the function is part of a class or not. | |
nsName:Namespace — The name of the namespace that you want to specify as public. You can apply the public attribute whether the namespace is part of a class or not. |
Example
How to use this example
The following example shows how you can use public variables in a class file:
class User { public var age:Number; public var fname:String; } // end of class User definition var jimmy:User = new User(); jimmy.age = 27; jimmy.fname = "jimmy"; trace(jimmy.age, jimmy.fname); // 27 jimmy
Related API Elements
return | Statements |
function functionName () { return [expression] } |
Causes execution to return immediately to the calling function. If the return
statement is followed by an expression, the expression is evaluated and the result is returned.
If a function definition includes a return type, the return
statement must be followed by an expression. If no return type is specified and the return
statement is used alone, it returns undefined
.
You cannot return multiple values. If you try to do so, only the last value is returned. In the following example, c
is returned:
return a, b, c ;
If you need to return multiple values, use an array or object instead.
Parametersexpression:* — An expression to evaluate and return as a value of the function. This parameter is optional. |
Example
How to use this example
The following example uses the return statement inside the body of the sum() function to return the added value of the three parameters. The next line of code calls sum() and assigns the returned value to the variable newValue.
function sum(a:Number, b:Number, c:Number):Number { return (a + b + c); } var newValue:Number = sum(4, 32, 78); trace(newValue); // 114
Related API Elements
set | Definition keywords |
function set property(newValue:*) : void{ // your statements here } |
Defines a setter, which is a method that appears in the public interface as a property.
A setter is a special method that sets the value of a property declared with the var
keyword.
Unlike other methods, a setter is called without parentheses (()
), which makes the setter appear to be a variable.
Setters allow you to apply the principle of information hiding by letting you create a public interface for a private property. The advantage of information hiding is that the public interface remains the same even if the underlying implementation of the private property changes.
Another advantage of setters is that they can be overridden in subclasses, whereas properties declared with var
cannot.
The return type of a setter must be either void
or not specified.
A setter can be combined with a getter to create a read-write property. To create a read-only property, create a getter without a corresponding setter. To create a write-only property, create a setter without a corresponding getter.
Parametersproperty:* — The identifier for the property that set modifies; this value must be the same as the value used in the corresponding get command. | |
newValue:* — The new value to assign. |
Example
How to use this example
The following example creates a read-write property named age by defining a getter-setter.
package { class User { private var userAge:Number; public function get age():Number { return userAge; } public function set age(x:Number):void { userAge = x; } } }
var myUser:User = new User(); myUser.age = 25; trace(myUser.age); // 25
Related API Elements
static | Attribute Keywords |
class someClassName{ static var varName; static const kName; static function methodName() { // your statements here } } |
Specifies that a variable, constant, or method belongs to the class, rather than to instances of the class.
To access a static class member, use the name of the class instead of the name of an instance. For example, the Date class has a static method named parse()
, which can only be called using the following syntax:
Date.parse()
The parse()
method cannot be called on an instance of the Date class. For example, the following code generates an error:
var myDate:Date = new Date(); myDate.parse("Jan 01 00:00:00 2006"); // error
You can use static
in class definitions only, not in interface definitions.
Static class members are not inherited. You cannot refer to a static class member using the name of a subclass, as you can in Java or C++. You can, however, refer to a static variable or method within a class or subclass, without using any qualifier. See the example below.
You cannot use the super
statement or the this
keyword inside a static method.
varName:* — The name of the variable that you want to specify as static. | |
kName:* — The name of the constant that you want to specify as static. | |
methodName:Function — The name of the method that you want to specify as static. |
Example
How to use this example
The following example demonstrates how you can use the static keyword to create a counter that tracks how many instances of the class have been created. Because the numInstances variable is static, it will be created only once for the entire class, not for every single instance. Create a new ActionScript file called Users.as and enter the following code:
class Users { private static var numInstances:Number = 0; function Users() { numInstances++; } static function get instances():Number { return numInstances; } }
trace(Users.instances); var user1:Users = new Users(); trace(Users.instances); var user2:Users = new Users(); trace(Users.instances);
class PowerUsers extends Users{ function PowerUsers() { instances++; // unqualified reference to static property Users.instances is legal } } trace(PowerUsers.instances); // error, cannot access static property using PowerUsers class
super | Statements |
super([arg1, ..., argN]) super.method([arg1, ..., argN]) |
Invokes the superclass or parent version of a method or constructor. When used within the body of a class constructor, the super()
statement invokes the superclass version of the constructor. The call to the superclass constructor must have the correct number of arguments. Note that the superclass constructor is always called, whether or not you call it explicitly. If you do not explicitly call it, a call with no arguments is automatically inserted before the first statement in the subclass constructor body. This means that if you define a constructor function in a subclass, and the superclass constructor takes one or more arguments, you must explicitly call the superclass constructor with the correct number of arguments or an error will occur. The call to the superclass constructor, however, does not need to be the first statement in your subclass constructor, as was required in ActionScript 2.0.
When used in the body of an instance method, super
can be used with the dot (.) operator to invoke the superclass version of a method and can optionally pass arguments (arg1 ... argN)
to the superclass method. This is useful for creating subclass methods that not only add additional behavior to superclass methods, but also invoke the superclass methods to perform their original behavior.
You cannot use the super
statement in a static method.
method:Function — The method to invoke in the superclass. | |
argN:* — Optional parameters that are passed to the superclass version of the method or to the constructor function of the superclass. |
Related API Elements
switch | Statements |
switch (expression) { caseClause: [defaultClause:] } |
Causes control to transfer to one of several statements, depending on the value of an expression. All switch
statements should include a default case that will execute if none of the case
statements match the expression. Each case
statement should end with a break
statement, which prevents a fall-through error. When a case falls through, it executes the code in the next case
statement, even though that case may not match the test expression.
expression:* — Any expression. |
Example
How to use this example
The following example defines a switch statement that falls through to the default case:
var switchExpression:int = 3; switch (switchExpression) { case 0: trace(0); break; case 1: trace(1); break; case 2: trace(2); break; default: trace("Not 0, 1, or 2"); } // Not 0, 1, or 2
Related API Elements
this | Primary expression keywords |
this |
A reference to a method's containing object. When a script executes, the this
keyword references the object that contains the script. Inside a method body, the this
keyword references the class instance that contains the called method.
Example
How to use this example
To call a function defined in a dynamic class, you must use this to invoke the function in the proper scope:
// incorrect version of Simple.as /* dynamic class Simple { function callfunc() { func(); } } */ // correct version of Simple.as dynamic class Simple { function callfunc() { this.func(); } }
var simpleObj:Simple = new Simple(); simpleObj.func = function() { trace("hello there"); } simpleObj.callfunc();
throw | Statements |
throw expression |
Generates, or throws, an error that can be handled, or caught, by a catch
code block. If an exception is not caught by a catch
block, the string representation of the thrown value is sent to the Output panel. If an exception is not caught by a catch
or finally
block, the string representation of the thrown value is sent to the log file.
Typically, you throw instances of the Error class or its subclasses (see the Example section).
Parametersexpression:* — An ActionScript expression or object. |
Example
How to use this example
In this example, a function named checkEmail() checks whether the string that is passed to it is a properly formatted e-mail address. If the string does not contain an @ symbol, the function throws an error.
function checkEmail(email:String) { if (email.indexOf("@") == -1) { throw new Error("Invalid email address"); } } checkEmail("someuser_theirdomain.com");
try { checkEmail("Joe Smith"); } catch (e) { trace(e); } // Error: Invalid email address.
// Define Error subclass InvalidEmailError class InvalidEmailAddress extends Error { public function InvalidEmailAddress() { message = "Invalid email address."; } }
import InvalidEmailAddress; function checkEmail(email:String) { if (email.indexOf("@") == -1) { throw new InvalidEmailAddress(); } } try { checkEmail("Joe Smith"); } catch (e) { trace(e); } // Error: Invalid email address.
More examples
Related API Elements
true | Primary expression keywords |
true |
A Boolean value representing true. A Boolean value is either true
or false
; the opposite of true
is false
. When automatic data typing converts true
to a number, it becomes 1; when it converts true
to a string, it becomes "true"
.
Example
How to use this example
The following example shows the use of true in an if statement:
var shouldExecute:Boolean; // ... // code that sets shouldExecute to either true or false goes here // shouldExecute is set to true for this example: shouldExecute = true; if (shouldExecute == true) { trace("your statements here"); } // true is also implied, so the if statement could also be written: // if (shouldExecute) { // trace("your statements here"); // }
var myNum:Number; myNum = 1 + true; trace(myNum); // 2
Related API Elements
try..catch..finally | Statements |
try { // try block } finally { // finally block } try { // try block } catch(error[:ErrorType1]) { // catch block } [catch(error[:ErrorTypeN]) { // catch block }] [finally { // finally block }] |
Encloses a block of code in which an error can occur, and then responds to the error.
Exception handling, which is implemented using the try..catch..finally
statements,
is the primary mechanism for handling runtime error conditions in ActionScript 3.0.
When a runtime error occurs, Flash Player throws an exception, which means that Flash Player suspends normal execution
and creates a special object of type Error
.
Flash Player then passes, or throws, the error object
to the first available catch
block. If no catch
blocks are available, the exception is
considered to be an uncaught exception. Uncaught exceptions cause the script to terminate.
You can use the throw
statement to explicitly throw exceptions in your code. You can throw any value, but
the best practice is to throw an object because it provides flexibility and matches the behavior of Flash Player.
To catch an exception, whether it is thrown by Flash Player or by your own code, place the code that may throw
the exception in a try
block. If any code in the try
block throws an exception,
control passes to the catch
block, if one exists, and then to the finally
block, if one exists.
The finally
block always executes, regardless of whether an exception was thrown.
If code within the try
block does not throw an exception (that is, if the try
block completes normally),
the code in the catch
block is ignored, but the code in the finally
block is still executed.
The finally
block executes even if the try
block exits using a return
statement.
A try
block must be followed by a catch
block, a finally
block, or both.
A single try
block can have multiple catch
blocks but only one finally
block.
You can nest try
blocks as many levels deep as desired.
The error
parameter specified in a catch
handler must be a simple identifier
such as e
or theException
or x
. The parameter can also be typed.
When used with multiple catch
blocks, typed parameters let you catch multiple types of error objects thrown
from a single try
block.
If the exception thrown is an object, the type will match if the thrown object is a subclass of the specified type.
If an error of a specific type is thrown, the catch
block that handles the corresponding error is executed.
If an exception that is not of the specified type is thrown, the catch
block does not execute and the exception
is automatically thrown out of the try
block to a catch
handler that matches it.
If an error is thrown within a function, and the function does not include a catch
handler,
Flash Player exits that function, as well as any caller functions, until a catch
block is found.
During this process, finally
handlers are called at all levels.
Note: If in a try block, there is an event dispatcher that calls its event handler,
the catch block doesn't catch the error if thrown in event handler. Any error thrown
thereafter can be caught by listening to LoaderInfo.uncaughtErrorEvents
.
error:* — The expression thrown from a throw statement, typically an instance of the Error class or one of its subclasses. |
Example
How to use this example
The following example demonstrates a try..catch statement. The code within the try block includes an illegal operation. A sprite cannot add itself as a child. As a result, Flash Player throws an exception, and passes an object of type ArgumentError to the corresponding catch block.
import flash.display.Sprite; var spr:Sprite = new Sprite(); try { spr.addChild(spr); } catch (e:ArgumentError) { trace (e); // ArgumentError: Error #2024: An object may not be added as a child of itself. }
class RecordSetException extends Error { public function RecordSetException () { message = "Record set exception occurred."; } } class MalformedRecord extends Error { public function MalformedRecord { message = "Malformed record exception occurred."; } }
class RecordSet { public function sortRows() { var returnVal:Number = randomNum(); if (returnVal == 1) { throw new RecordSetException(); } else if (returnVal == 2) { throw new MalformedRecord(); } } public function randomNum():Number { return Math.round(Math.random() * 10) % 3; } }
import RecordSet; var myRecordSet:RecordSet = new RecordSet(); try { myRecordSet.sortRows(); trace("everything is fine"); } catch (e:RecordSetException) { trace(e.toString()); } catch (e:MalformedRecord) { trace(e.toString()); }
More examples
Related API Elements
use namespace | Directives |
use namespace ns1[, ns2, ...nsN] |
Causes the specified namespaces to be added to the set of open namespaces.
The specified namespaces are removed from the set of open namespaces when the current code block is exited.
The use namespace
directive can appear at the top level of a program, package definition, or class definition.
nsN:Namespace — One or more namespaces to add to the set of open namespaces. |
Related API Elements
var | Definition keywords |
var variableName [= value1][...,variableNameN[=valueN]] |
Specifies a variable. If you declare variables inside a function, the variables are local. They are defined for the function and expire at the end of the function call.
You cannot declare a variable that is in the scope of another object as a local variable.
my_array.length = 25; // ok var my_array.length = 25; // syntax error
You can assign a data type to a variable by appending a colon character followed by the data type.
You can declare multiple variables in one statement, separating the declarations with commas (although this syntax may reduce clarity in your code):
var first:String = "Bart", middle:String = "J.", last:String = "Bartleby";Parameters
variableName:* — An identifier. |
Example
How to use this example
The following ActionScript creates a new array of product names. Array.push adds an element onto the end of the array.
var product_array:Array = new Array("Studio", "Dreamweaver", "Flash", "ColdFusion", "Contribute", "Breeze"); product_array.push("Flex"); trace(product_array); // Studio,Dreamweaver,Flash,ColdFusion,Contribute,Breeze,Flex
Related API Elements
while | Statements |
while (condition) { // statement(s) } |
Evaluates a condition and if the condition evaluates to true
, executes one or more statements before looping back to evaluate the condition again.
After the condition evaluates to false
, the statements are skipped and the loop ends.
The while
statement performs the following series of steps. Each repetition of steps 1 through 4 is called an iteration of the loop.
The condition is tested at the beginning of each iteration, as shown in the following steps:
- The expression
condition
is evaluated. - If
condition
evaluates totrue
or a value that converts to the Boolean valuetrue
, such as a nonzero number, go to step 3. Otherwise, thewhile
statement is completed and execution resumes at the next statement after thewhile
loop. - Run the statement block
statement(s)
. If acontinue
statement is encountered, skip the remaining statements and go to step 1. If abreak
statement is encountered, thewhile
statement is completed and execution resumes at the next statement after thewhile
loop. - Go to step 1.
Looping is commonly used to perform an action while a counter variable is less than a specified value.
At the end of each loop, the counter is incremented until the specified value is reached.
At that point, the condition
is no longer true
, and the loop ends.
The curly braces ({}
) that enclose the statements to be executed by the while
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 while statement is used to test an expression. When the value of i is less than 20, the value of i is traced. When the condition is no longer true, the loop exits.
var i:Number = 0; while (i < 20) { trace(i); i += 3; } /* 0 3 6 9 12 15 18 */
Related API Elements
with | Statements |
with (object:Object) { // statement(s) } |
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.
The object
parameter becomes the context in which the properties, variables, and functions in the statement(s)
parameter are read. For example, if object
is my_array
, and two of the properties specified are length
and concat
, those properties are automatically read as my_array.length
and my_array.concat
. In another example, if object
is state.california
, any actions or statements inside the with
statement are called from inside the california
instance.
To find the value of an identifier in the statement(s)
parameter, ActionScript starts at the beginning of the scope chain specified by object
and searches for the identifier at each level of the scope chain, in a specific order.
The scope chain used by the with
statement to resolve identifiers starts with the first item in the following list and continues to the last item:
- The object specified in the
object
parameter in the innermostwith
statement - The object specified in the
object
parameter in the outermostwith
statement - The Activation object (a temporary object that is automatically created when the script calls a function that holds the local variables called in the function)
- The object that contains the currently executing script
- The Global object (built-in objects such as Math and String)
To set a variable inside a with
statement, you must have declared the variable outside the with
statement, or you must enter the full path to the Timeline on which you want the variable to live. If you set a variable in a with
statement without declaring it, the with
statement will look for the value according to the scope chain.
If the variable doesn't already exist, the new value will be set on the Timeline from which the with
statement was called.
object:Object — An instance of an ActionScript object or movie clip. |
Example
How to use this example
The following example sets the _x and _y properties of the someOther_mc instance, and then instructs someOther_mc to go to Frame 3 and stop. with (someOther_mc) { _x = 50; _y = 100; gotoAndStop(3); } The following code snippet shows how to write the preceding code without using a with statement. someOther_mc._x = 50; someOther_mc._y = 100; someOther_mc.gotoAndStop(3); The with statement is useful for accessing multiple items in a scope chain list simultaneously. In the following example, the built-in Math object is placed at the front of the scope chain. Setting Math as a default object resolves the identifiers cos, sin, and PI to Math.cos, Math.sin, and Math.PI, respectively. The identifiers a, x, y, and r are not methods or properties of the Math object, but because they exist in the object activation scope of the function polar(), they resolve to the corresponding local variables.
function polar(r:Number):void { var a:Number, x:Number, y:Number; with (Math) { a = PI * pow(r, 2); x = r * cos(PI); y = r * sin(PI / 2); } trace("area = " + a); trace("x = " + x); trace("y = " + y); } polar(3); /* area = 28.2743338823081 x = -3 y = 3 */
Wed Nov 21 2018, 07:01 AM -08:00