Statements are language elements that perform or specify an action. For example, the return statement returns a result as a value of 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.
Statement summary | ||
---|---|---|
break | Appears within a loop (for , for..in , do..while or while ) or within a block of statements associated with a particular case within a switch statement. |
|
case | Defines a condition for the switch statement. |
|
class | Defines a custom class, which lets you instantiate objects that share methods and properties that you define. | |
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. |
|
delete | Destroys the object reference specified by the reference parameter, and returns true if the reference is successfully deleted; false otherwise. |
|
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 . |
|
else if | Evaluates a condition and specifies the statements to run if the condition in the initial
if statement returns false . |
|
for | Evaluates the init (initialize) expression once and then starts a looping sequence. |
|
for..in | Iterates over the properties of an object or elements in an array and executes the statement for each property or element. |
|
function | Comprises a set of statements that you define to perform a certain task. | |
if | Evaluates a condition to determine the next action in a SWF file. | |
return | Specifies the value returned by a function. | |
set variable | Assigns a value to a variable. | |
super | Invokes the superclass' version of a method or constructor. | |
switch | Creates a branching structure for ActionScript statements. | |
throw | Generates, or throws , an error that can be handled, or caught , by a
catch{} code block. |
|
try..catch..finally | Enclose a block of code in which an error can occur, and then respond to the error. | |
var | Used to declare local or Timeline variables. | |
while | Evaluates a condition and if the condition evaluates to true , runs a statement or series of statements before looping back to evaluate the condition again. |
|
with | Lets you specify an object (such as a movie clip) with the object parameter and evaluate expressions and actions inside that object with the statement(s) parameter. |
|
Keyword summary | ||
dynamic | Specifies that objects based on the specified class can add and access dynamic properties at runtime. | |
extends | Defines a class that is a subclass of another class; the latter is the superclass. | |
get | Permits implicit getting of properties associated with objects based on classes you have defined in external class files. | |
implements | Specifies that a class must define all the methods declared in the interface (or interfaces) being implemented. | |
import | Lets you access classes without specifying their fully qualified names. | |
interface | Defines an interface. | |
intrinsic | Allows compile-time type checking of previously defined classes. | |
private | Specifies that a variable or function is available only to the class that declares or defines it or to subclasses of that class. | |
public | Specifies that a variable or function is available to any caller. | |
set | Permits implicit setting of properties associated with objects based on classes you have defined in external class files. | |
static | Specifies that a variable or function is created only once per class rather than being created in every object based on that class. |
break | statement |
break |
Player version: | Flash Player 4 |
Appears within a loop (for
, for..in
, do..while
or while
) or within a block of statements associated with a particular case within 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 following the enclosing switch
statement.
In nested loops, the break
statement only skips the rest of the immediate loop and does not break out of the entire series of nested loops. For breaking out of an entire series of nested loops, see try..catch..finally
.
break
statement to exit an otherwise infinite loop: var i:Number = 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
See also
case | statement |
case expression : statement(s) |
Player version: | Flash Player 4 |
Defines a condition for the switch
statement. If the expression
parameter equals the expression
parameter of the switch
statement using strict equality
(===
), then Flash Player will execute statements in the statement(s)
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.
statement(s)
parameter with a break statement. If you omit the break statement
from the statement(s)
parameter, it continues executing with the next case
statement instead of exiting the switch
statement.
expression:String —
Any expression.
|
thisMonth
. If
thisMonth
equals the expression in the case statement, the statement executes. var thisMonth:Number = 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"); }
See also
class | statement |
[dynamic] class className [ extends superClass ] [ implements interfaceName[, interfaceName... ] ] { // class definition here } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Defines a custom 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.
The name of the class must match the name of the external file that contains the class. The name of the external 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.
If a class is within a package, the class declaration must use the fully qualified class name of the form base.sub1.sub2.MyClass. Also, the class's AS file must be stored within the path in a directory structure that reflects the package structure, such as base/sub1/sub2/MyClass.as. If a class definition is of the form "class MyClass," it is in the default package and the MyClass.as file should be in the top level of some directory in the path.
For this reason, it's good practice to plan your directory structure before you begin creating classes. Otherwise, if you decide to move class files after you create them, you have to modify the class declaration statements to reflect their new location.
You cannot nest class definitions; that is, you cannot define additional classes within a class definition.
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:String —
The fully qualified name of the class.
|
// Filename Plant.as class Plant { // Define property names and types var leafType:String; var bloomSeason:String; // Following line is constructor // because it has the same name as the class function Plant(param_leafType:String, param_bloomSeason:String) { // Assign passed values to properties when new Plant object is created this.leafType = param_leafType; this.bloomSeason = param_bloomSeason; } // Create methods to return property values, because best practice // recommends against directly referencing a property of a class function getLeafType():String { return leafType; } function getBloomSeason():String { return bloomSeason; } }
new
operator to create a Plant object. In your script, use the new
operator to create a Plant object. var pineTree:Plant = new Plant("Evergreen", "N/A"); // Confirm parameters were passed correctly trace(pineTree.getLeafType()); trace(pineTree.getBloomSeason());
ImageLoader
constructor takes three parameters. // Filename ImageLoader.as class ImageLoader extends MovieClip { function ImageLoader(image:String, target_mc:MovieClip, init:Object) { var listenerObject:Object = new Object(); listenerObject.onLoadInit = function(target) { for (var i in init) { target[i] = init[i]; } }; var JPEG_mcl:MovieClipLoader = new MovieClipLoader(); JPEG_mcl.addListener(listenerObject); JPEG_mcl.loadClip(image, target_mc); } }
new
operator to create an ImageLoader object. In your script, use the new
operator to create an ImageLoader object.
var jakob_mc:MovieClip = this.createEmptyMovieClip("jakob_mc", this.getNextHighestDepth()); var jakob:ImageLoader = new ImageLoader("http://www.helpexamples.com/flash/images/image1.jpg", jakob_mc, {_x:10, _y:10, _alpha:70, _rotation:-5});
See also
continue | statement |
continue |
Player version: | Flash Player 4 |
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. It has no effect outside a loop.
while
loop, continue
causes the Flash interpreter to skip the rest of the loop body and jump to the top of the loop, where the condition is tested: trace("example 1"); var i:Number = 0; while (i < 10) { if (i % 3 == 0) { i++; continue; } trace(i); i++; }
In the following do..while
loop, continue
causes the Flash interpreter to skip the rest of the loop body and jump to the bottom of the loop, where the condition is tested:
trace("example 2"); var i:Number = 0; do { if (i % 3 == 0) { i++; continue; } trace(i); i++; } while (i < 10);
In a for
loop, continue
causes the Flash interpreter to skip the rest of the loop body. In the following example, if the i modulo 3 equals 0, then the trace(i)
statement is skipped:
trace("example 3"); for (var i = 0; i < 10; i++) { if (i % 3 == 0) { continue; } trace(i); }
In the following for..in
loop, continue
causes the Flash interpreter to skip the rest of the loop body and jump back to the top of the loop, where the next value in the enumeration is processed:
for (i in _root) { if (i == "$version") { continue; } trace(i); }
See also
default | statement |
default: statements |
Player version: | Flash Player 6 |
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
is not required to have 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:String —
Any statements.
|
default
keyword is run and the trace()
statement is sent to the Output paneland the trace()
statement is sent to the log file. var dayOfWeek:Number = 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"); }
See also
delete | statement |
delete reference |
Player version: | Flash Player 5 |
Destroys the object reference specified by the reference
parameter, and returns true
if the reference is successfully deleted; false
otherwise. This operator is useful for freeing memory used by scripts. You can use the delete
operator to remove references to objects. After all references to an object are removed, Flash Player removes the object and frees the memory used by that object.
Although delete
is an operator, it is typically used as a statement, as shown in the following example:
delete x;
The delete
operator can fail and return false
if the reference
parameter does not exist or cannot be deleted. You cannot delete predefined objects and properties, and you cannot delete variables that are declared within a function with the var
statement. You cannot use the delete
operator to remove movie clips.
reference:Object —
The name of the variable or object to eliminate.
|
Boolean — A Boolean value. |
Usage 1: The following example creates an object, uses it, and deletes it when it is no longer needed:
var account:Object = new Object(); account.name = "Jon"; account.balance = 10000; trace(account.name); //output: Jon delete account; trace(account.name); //output: undefined
Usage 2: The following example deletes a property of an object:
// create the new object "account" var account:Object = new Object(); // assign property name to the account account.name = "Jon"; // delete the property delete account.name;
Usage 3: The following example deletes an object property:
var my_array:Array = new Array(); my_array[0] = "abc"; // my_array.length == 1 my_array[1] = "def"; // my_array.length == 2 my_array[2] = "ghi"; // my_array.length == 3 // my_array[2] is deleted, but Array.length is not changed delete my_array[2]; trace(my_array.length); // output: 3 trace(my_array); // output: abc,def,undefined
Usage 4: The following example shows the behavior of delete
on object references:
var ref1:Object = new Object(); ref1.name = "Jody"; // copy the reference variable into a new variable // and delete ref1 ref2 = ref1; delete ref1; trace("ref1.name "+ref1.name); //output: ref1.name undefined trace("ref2.name "+ref2.name); //output: ref2.name Jody
If ref1
had not been copied into ref2
, the object would have been deleted when ref1
was deleted because there would be no references to it. If you delete ref2
, there are no references to the object; it is destroyed, and the memory it used becomes available.
Usage 5: The following example shows how the returned Boolean from delete
can be used as a condition for future code execution. If an item has already been deleted, calling delete
on the item again will return false
.
var my_array:Array = [ "abc", "def", "ghi" ]; var deleteWasSuccessful:Boolean deleteWasSuccessful = delete my_array[0]; if(deleteWasSuccessful) delete my_array[1]; deleteWasSuccessful = delete my_array[0]; if(deleteWasSuccessful) delete my_array[2]; trace(my_array) // outputs: undefined,undefined,ghi
See also
do..while | statement |
do { statement(s) } while (condition) |
Player version: | Flash Player 4 |
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 is executed at least once. Although this can also be done 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, you should use a for
loop if you know the number of times that 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 are executed as long as the condition parameter evaluates to true .
|
The following example uses a do..while
loop to evaluate whether a condition is
true,
and traces myVar
until myVar
is greater than 5. When myVar
is greater than 5, the loop ends.
var myVar:Number = 0; do { trace(myVar); myVar++; } while (myVar < 5); /* output: 0 1 2 3 4 */
See also
dynamic | keyword |
dynamic class className [ extends superClass ] [ implements interfaceName[, interfaceName... ] ] { // class definition here } |
Language version: | ActionScript 2.0 — This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Specifies that objects based on the specified class can add and access dynamic properties at runtime.
Type checking on dynamic classes is less strict than type checking on nondynamic classes, because members accessed inside the class definition and on class instances are not compared with those defined in the class scope. Class member functions, however, can still be type checked for return type and parameter types. This behavior is especially useful when you work with MovieClip objects, because there are many different ways of adding properties and objects to a movie clip dynamically, such as MovieClip.createEmptyMovieClip()
and MovieClip.createTextField()
.
Subclasses of dynamic classes are also dynamic.
Be sure to specify the type when declaring an object, as in the following:
var x:MyClass = new MyClass();
var x = new MyClass();
Person2
has not yet been marked as dynamic, so calling an undeclared function on it generates an error at compile time: class Person2 { var name:String; var age:Number; function Person2(param_name:String, param_age:Number) { trace ("anything"); this.name = param_name; this.age = param_age; } }
// Before dynamic is added var craig:Person2 = new Person2("Craiggers", 32); for (i in craig) { trace("craig." + i + " = " + craig[i]); } /* output: craig.age = 32 craig.name = Craiggers */
dance
, an error is generated, as shown in the following example: trace(""); craig.dance = true; for (i in craig) { trace("craig." + i + " = " + craig[i]); } /* output: **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 14: There is no property with the name 'dance'. craig.dance = true; Total ActionScript Errors: 1 Reported Errors: 1 */
dynamic
keyword to the Person2 class, so that the first line appears as follows: dynamic class Person2 {
craig.dance = true craig.age = 32 craig.name = Craiggers
See also
else | statement |
if (condition){ statement(s); } else { statement(s); } |
Player version: | Flash Player 4 |
Specifies the statements to run if the condition in the if
statement returns
false
. The curly braces ({}
) used to enclose the block of 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 .
|
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; }
In the following example, curly braces ({})
are not necessary because only one statement follows the
else
statement:
if (age_txt.text>18) { trace("welcome, user"); } else trace("sorry, junior");
See also
else if | statement |
if(condition) { statement(s); } else if(condition) { statement(s); } |
Player version: | Flash Player 4 |
Evaluates a condition and specifies the statements to run if the condition in the initial
if
statement returns false
. If the else if
condition returns true
, the Flash interpreter runs the statements that follow the condition inside curly braces ({}
). If the else if
condition is false
, Flash skips the statements inside the curly braces and runs the statements following the curly braces.
Use the else
if
statement to create branching logic in your scripts. If there are multiple branches, you should consider using a switch
statement.
condition:Boolean —
An expression that evaluates to true or false .
|
The following example uses else if
statements to compare score_txt
to a specified value:
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"); }
See also
extends | keyword |
class className extends otherClassName {} interface interfaceName extends otherInterfaceName {} |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Defines a class that is a subclass of another class; the latter is the superclass. The subclass inherits all the methods, properties, functions, and so on that are defined in the superclass.
Interfaces can also be extended by using the extends
keyword. An interface that extends another interface includes all of the method declarations of the original interface.
className:String —
The name of the class that you are defining.
|
The following example shows the contents of a file called Vehicle.as, which defines the Vehicle class:
class Vehicle { var numDoors:Number; var color:String; function Vehicle(param_numDoors:Number, param_color:String) { this.numDoors = param_numDoors; this.color = param_color; } function start():Void { trace("[Vehicle] start"); } function stop():Void { trace("[Vehicle] stop"); } function reverse():Void { trace("[Vehicle] reverse"); } }
The following example shows a second AS file, called Car.as, in the same directory. This class extends the Vehicle class, modifying it in three ways. First, the Car class adds a variable fullSizeSpare
to track whether the car object has a full-size spare tire. Second, it adds a new method specific to cars, activateCarAlarm()
, which activates the car's antitheft alarm. Third, it overrides the stop()
function to add the fact that the Car class uses an antilock braking system to stop.
class Car extends Vehicle { var fullSizeSpare:Boolean; function Car(param_numDoors:Number, param_color:String, param_fullSizeSpare:Boolean) { this.numDoors = param_numDoors; this.color = param_color; this.fullSizeSpare = param_fullSizeSpare; } function activateCarAlarm():Void { trace("[Car] activateCarAlarm"); } function stop():Void { trace("[Car] stop with anti-lock brakes"); } }
The following example instantiates a Car object, calls a method that is defined in the Vehicle class
(start()
), then calls the method that is overridden by the Car class (stop()
), and finally calls a method from the Car class (activateCarAlarm()
):
var myNewCar:Car = new Car(2, "Red", true); myNewCar.start(); // output: [Vehicle] start myNewCar.stop(); // output: [Car] stop with anti-lock brakes myNewCar.activateCarAlarm(); // output: [Car] activateCarAlarm
A subclass of the Vehicle class can also be written by using the keyword super
, which the subclass can use to access properties and methods of the superclass. The following example shows a third AS file, called Truck.as, again in the same directory. The Truck class uses the super
keyword in the constructor and again in the overridden reverse()
function.
class Truck extends Vehicle { var numWheels:Number; function Truck(param_numDoors:Number, param_color:String, param_numWheels:Number) { super(param_numDoors, param_color); this.numWheels = param_numWheels; } function reverse():Void { beep(); super.reverse(); } function beep():Void { trace("[Truck] make beeping sound"); } }
The following example instantiates a Truck object, calls a method overridden by the Truck class (reverse()
), and then calls a method defined in the Vehicle class (stop()
):
var myTruck:Truck = new Truck(2, "White", 18); myTruck.reverse(); // output: [Truck] make beeping sound [Vehicle] reverse myTruck.stop(); // output: [Vehicle] stop
See also
for | statement |
for(init; condition; next) { statement(s); } |
Player version: | Flash Player 5 |
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 the next
expression is evaluated. The looping sequence then begins again with the evaluation of the condition
expression.
The curly braces
({}
) used to enclose the block of statements to be executed by the for
statement are not necessary if only one statement will execute.
init —
An expression to evaluate before beginning the looping sequence; usually an assignment expression. A var statement is also permitted for this parameter.
|
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); // output: 50,60,70,80,90,100,110,120,130,140
50 60 70 80 90 100 110 120 130 140
for
to perform the same action repeatedly. In the code, the for
loop adds the numbers from 1 to 100. var sum:Number = 0; for (var i:Number = 1; i <= 100; i++) { sum += i; } trace(sum); // output: 5050
var sum:Number = 0; for (var i:Number = 1; i <= 100; i++) sum += i; trace(sum); // output: 5050
See also
for..in | statement |
for (variableIterant in object) { statement(s); } |
Player version: | Flash Player 5 |
Iterates over the properties of an object or elements in an array and executes the statement
for each property or element. Methods of an object are not enumerated by the for..in
action.
Some properties cannot be enumerated by the for..in
action. For example, movie clip properties, such as _x
and
_y
, are not enumerated. In external class files, static members are not enumerable, unlike instance members.
The for..in
statement iterates over properties of objects in the iterated object's prototype chain. Properties of the object are enumerated first, then properties of its immediate prototype, then properties of the prototype's prototype, and so on. It iterates over the properties in reverse index order. The for..in
statement does not enumerate the same property name twice. If the object child
has prototype parent
and both contain the property prop
, the for..in
statement called on child
enumerates prop
from child
but ignores the one in parent
.
The curly braces ({}
) that are used to enclose the block of statements to be executed by the for..in
statement are not necessary if only one statement is executed.
If you write a for..in
loop in a class file (an external AS file), then instance members are not available for the loop, but static members are. However, if you write a for..in
loop in a FLA file for an instance of the class, then instance members are available but static ones are not.
variableIterant:String —
The name of a variable to act as the iterant, referencing each property of an object or element in an array.
|
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]); } //output myObject.firstName = Tara myObject.age = 27 myObject.city = San Francisco
The following example uses for..in
to iterate over the elements of an array:
var myArray:Array = new Array("one", "two", "three"); for (var index in myArray) trace("myArray["+index+"] = " + myArray[index]); // output: myArray[2] = three myArray[1] = two myArray[0] = one
The following example uses the typeof
operator with for..in
to iterate over a particular type of child:
for (var name in this) { if (typeof (this[name]) == "movieclip") { trace("I have a movie clip child named "+name); } }
Note: If you have several movie clips, the output consists of the instance names of those clips.
The following example enumerates the children of a movie clip and sends each to Frame 2 in its
respective Timeline. The RadioButtonGroup
movie clip is a parent with three children: _RedRadioButton_
, _GreenRadioButton_,
, and _BlueRadioButton_
.
for (var name in RadioButtonGroup) { RadioButtonGroup[name].gotoAndStop(2); }
function | statement |
Usage 1: (Declares a named function.) function functionname([parameter0, parameter1,...parameterN]){ statement(s) } Usage 2: (Declares an anonymous function and returns a reference to it.) function ([parameter0, parameter1,...parameterN]){ statement(s) } |
Player version: | Flash Player 5 |
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 a function in different situations.
Use the return
statement in a function's statement(s)
to cause a function to generate, or return, a value.
You can use this statement to define a function
with the specified functionname
,
parameters
, and statement(s)
. 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 previous definition of the same function. You can use this syntax wherever a statement is permitted.
You can use the function statement 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. Some common uses of the
arguments
object are to create a function that accepts a variable number of parameters and to create a recursive anonymous function.
functionname:String —
The name of the declared function.
|
String — Usage 1: The declaration form does not return anything. Usage 2: A reference to the anonymous function. |
The following example defines the function sqr
, which accepts one parameter and returns the Math.pow(x, 2)
of the parameter:
function sqr(x:Number) { return Math.pow(x, 2); } var y:Number = sqr(3); trace(y); // output: 9
If the function is defined and used in the same script, the function definition may appear after using the function:
var y:Number = sqr(3); trace(y); // output: 9 function sqr(x:Number) { return Math.pow(x, 2); }
The following function creates a LoadVars object and loads params.txt into the SWF file. When the file successfully loads, variables loaded
traces:
var myLV:LoadVars = new LoadVars(); myLV.load("params.txt"); myLV.onLoad = function(success:Boolean) { trace("variables loaded"); }
get | keyword |
function get property () { // your statements here } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Permits implicit getting of properties associated with objects based on classes you have defined in external class files. Using implicit get methods lets you access properties of objects without accessing the property directly. Implicit get/set methods are syntactic shorthand for the Object.addProperty()
method in ActionScript 1.0.
property:String —
The word you use to refer to the property that get accesses; this value must be the same as the value used in the corresponding set command.
|
class Team { var teamName:String; var teamCode:String; var teamPlayers:Array = new Array(); function Team(param_name:String, param_code:String) { this.teamName = param_name; this.teamCode = param_code; } function get name():String { return this.teamName; } function set name(param_name:String):Void { this.teamName = param_name; } }
var giants:Team = new Team("San Fran", "SFO"); trace(giants.name); giants.name = "San Francisco"; trace(giants.name); /* output: San Fran San Francisco */
When you trace giants.name, you use the get
method to return the value of the property.
See also
if | statement |
if(condition) { statement(s); } |
Player version: | Flash Player 4 |
Evaluates a condition to determine the next action in a SWF file. If the condition is
true
, Flash runs the statements that follow the condition inside curly braces ({}
). If the condition is false
, Flash skips the statements inside the curly braces and runs the statements following the curly braces. Use the if
statement along with the else
and else if
statements to create branching logic in your scripts.
The curly braces ({}
) used to enclose the block of 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 .
|
name
to see if it has the literal value "Erica"
. If it does, the play()
function inside the curly braces runs. if(name == "Erica"){ play(); }
The following example uses an if
statement to evaluate how long it takes a user to click the submit_btn
instance in a SWF file. If a user clicks the button more than 10 seconds after the SWF file plays, the condition evaluates to true
and the message inside the curly braces ({}
) appears in a text field that's created at runtime (using createTextField()
). If the user clicks the button less than 10 seconds after the SWF file plays, the condition evaluates to false
and a different message appears.
this.createTextField("message_txt", this.getNextHighestDepth, 0, 0, 100, 22); message_txt.autoSize = true; var startTime:Number = getTimer(); this.submit_btn.onRelease = function() { var difference:Number = (getTimer() - startTime) / 1000; if (difference > 10) { this._parent.message_txt.text = "Not very speedy, you took "+difference+" seconds."; } else { this._parent.message_txt.text = "Very good, you hit the button in "+difference+" seconds."; } };
See also
implements | keyword |
myClass implements interface01 [, interface02 , ...] |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Specifies that a class must define all the methods declared in the interface (or interfaces) being implemented.
interface
.
See also
import | keyword |
import className import packageName.* |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Lets you access classes without specifying their fully qualified names. For example, if you want to use a custom class macr.util.users.UserClass in a script, you must refer to it by its fully qualified name or import it; if you import it, you can refer to it by the class name:
// before importing var myUser:macr.util.users.UserClass = new macr.util.users.UserClass(); // after importing import macr.util.users.UserClass; var myUser:UserClass = new UserClass();
If there are several class files in the package
(working_directory
/macr/utils/users
) that you want to access, you can import them all in a single statement, as shown in the following example:
import macr.util.users.*;
You must issue the
import
statement before you try to access the imported class without fully specifying its name.
If you import a class but don't use it in your script, the class isn't 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.
The import
statement applies only to the current script (frame or object) in which it's called. For example, suppose on Frame 1 of a Flash document you import all the classes in the macr.util package. On that frame, you can reference classes in that package by their simple names:
// On Frame 1 of a FLA: import macr.util.*; var myFoo:foo = new foo();
On another frame script, however, you would need to reference classes in that package by their fully qualified names (var myFoo:foo = new macr.util.foo();
) or add an import
statement to the other frame that imports the classes in that package.
className:String —
The fully qualified name of a class you have defined in an external class file.
|
interface | keyword |
interface InterfaceName [extends InterfaceName ] {} |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Defines an interface. An interface is similar to a class, with the following important differences:
get
and set
statements are not allowed in interface definitions.(in top-level package .as files Ia, B, C, Ib, D, Ic, E) // filename Ia.as interface Ia { function k():Number; // method declaration only function n(x:Number):Number; // without implementation } // filename B.as class B implements Ia { function k():Number { return 25; } function n(x:Number):Number { return x + 5; } } // external script or Actions panel // script file var mvar:B = new B(); trace(mvar.k()); // 25 trace(mvar.n(7)); // 12 // filename c.as class C implements Ia { function k():Number { return 25; } } // error: class must implement all interface methods // filename Ib.as interface Ib { function o():Void; } class D implements Ia, Ib { function k():Number { return 15; } function n(x:Number):Number { return x * x; } function o():Void { trace("o"); } } // external script or Actions panel // script file mvar = new D(); trace(mvar.k()); // 15 trace(mvar.n(7)); // 49 trace(mvar.o()); // "o" interface Ic extends Ia { function p():Void; } class E implements Ib, Ic { function k():Number { return 25; } function n(x:Number):Number { return x + 5; } function o():Void { trace("o"); } function p():Void { trace("p"); } }
See also
intrinsic | keyword |
intrinsic class className [extends superClass] [implements interfaceName [, interfaceName...] ] { //class definition here } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Allows compile-time type checking of previously defined classes. Flash uses intrinsic class declarations to enable compile-time type checking of built-in classes such as Array
, Object
, and
String
. This keyword indicates to the compiler that no function implementation is required, and that no bytecode should be generated for it.
The intrinsic
keyword can also be used with variable and function declarations. Flash uses this keyword to enable compile-time type checking for global functions and properties.
The intrinsic
keyword was created specifically to enable compile-time type checking for built-in classes and objects, and global variables and functions. This keyword was not meant for general purpose use, but may be of some value to developers seeking to enable compile-time type checking with previously defined classes, especially if the classes are defined using ActionScript 1.0.
This keyword is supported only when used in external script files, not in scripts written in the Actions panel.
myCircle.setRadius()
sends a String
value as a parameter instead of a Number
value. You can avoid the error by changing the parameter to a Number
value (for example, by changing "10"
to 10
).
// The following code must be placed in a file named Circle.as // that resides within your classpath: intrinsic class Circle { var radius:Number; function Circle(radius:Number); function getArea():Number; function getDiameter():Number; function setRadius(param_radius:Number):Number; } // This ActionScript 1.0 class definition may be placed in your FLA file. // Circle class is defined using ActionScript 1.0 function Circle(radius) { this.radius = radius; this.getArea = function(){ return Math.PI*this.radius*this.radius; }; this.getDiameter = function() { return 2*this.radius; }; this.setRadius = function(param_radius) { this.radius = param_radius; } } // ActionScript 2.0 code that uses the Circle class var myCircle:Circle = new Circle(5); trace(myCircle.getArea()); trace(myCircle.getDiameter()); myCircle.setRadius("10"); trace(myCircle.radius); trace(myCircle.getArea()); trace(myCircle.getDiameter());
See also
private | keyword |
class someClassName{ private var name; private function name() { // your statements here } } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Specifies that a variable or function is available only to the class that declares or defines it or to subclasses of that class. By default, a variable or function is available to any caller. Use this keyword if you want to restrict access to a variable or function. This keyword is intended as a software development aid to facilitate good coding practices such as encapsulation, and not as a security mechanism to obfuscate or secure sensitive data. It does not necessarily prevent access to a variable at runtime.
You can use this keyword only in class definitions, not in interface definitions.
Parametersname:String —
The name of the variable or function that you want to specify as private.
|
private
keyword. Create a new AS file called Alpha.as:
class Alpha { private var privateProperty = "visible only within class and subclasses"; public var publicProperty = "visible everywhere"; }
In the same directory as Alpha.as, create a new AS file named Beta.as that contains the following code:
class Beta extends Alpha { function Beta() { trace("privateProperty is " + privateProperty); } }
As the following code demonstrates, the constructor for the Beta class is able to access the privateProperty
property that is inherited from the Alpha class:
var myBeta:Beta = new Beta(); // Output: privateProperty is visible only within class and subclasses
Attempts to access the privateProperty
variable from outside the Alpha class or a class that inherits from the Alpha class result in an error. The following code, which resides outside of any class, causes an error:
trace(myBeta.privateProperty); // Error
See also
public | keyword |
class someClassName{ public var name; public function name() { // your statements here } } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Specifies that a variable or function is available to any caller. Because variables and functions are public by default, this keyword is used primarily for stylistic reasons. For example, you might want to use it for reasons of consistency in a block of code that also contains private or static variables.
Parametersname:String —
The name of the variable or function that you want to specify as public.
|
class User { public var age:Number; public var name:String; }
Then create a new FLA or AS file in the same directory, and enter the following ActionScript in Frame 1 of the Timeline:
import User; var jimmy:User = new User(); jimmy.age = 27; jimmy.name = "jimmy";
If you change one of the public variables in the User class to a private variable, an error is generated when trying to access the property.
See also
return | statement |
return[expression] |
Player version: | Flash Player 5 |
Specifies the value returned by a function. The return
statement evaluates expression
and returns the result as a value of the function in which it executes. The return
statement causes execution to return immediately to the calling function. If the return
statement is used alone, it returns
undefined.
You can't 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, you might want to use an array or object instead.
Parametersexpression —
A string, number, Boolean, array, or object to evaluate and return as a value of the function. This parameter is optional.
|
String — The evaluated expression parameter, if provided. |
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); // output: 114
See also
set | keyword |
function set property(varName) { // your statements here } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Permits implicit setting of properties associated with objects based on classes you have defined in external class files. Using implicit set methods lets you modify the value of an object's property without accessing the property directly. Implicit get/set methods are syntactic shorthand for the Object.addProperty()
method in ActionScript 1.0.
property:String —
Word that refers to the property that set will access; this value must be the same as the value used in the corresponding get command.
|
set
keyword can be used to set private variables: class Login { private var loginUserName:String; private var loginPassword:String; public function Login(param_username:String, param_password:String) { this.loginUserName = param_username; this.loginPassword = param_password; } public function get username():String { return this.loginUserName; } public function set username(param_username:String):Void { this.loginUserName = param_username; } public function set password(param_password:String):Void { this.loginPassword = param_password; } }
In a FLA or AS file that is in the same directory as Login.as, enter the following ActionScript in Frame 1 of the Timeline:
var gus:Login = new Login("Gus", "Smith"); trace(gus.username); // output: Gus gus.username = "Rupert"; trace(gus.username); // output: Rupert
In the following example, the get
function executes when the value is traced. The set
function triggers only when you pass it a value, as shown in the line:
gus.username = "Rupert";
See also
set variable | statement |
set("variableString",expression) |
Player version: | Flash Player 4 |
Assigns a value to a variable. A variable is a container that holds data. The container is always the same, but the contents can change. By changing the value of a variable as the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is true
or false
.
Variables can hold any data type (for example, String, Number, Boolean, Object, or MovieClip). The Timeline of each SWF file and movie clip has its own set of variables, and each variable has its own value independent of variables on other Timelines.
Strict data typing is not supported inside a set
statement. If you use this statement to set a variable to a value whose data type is different from the data type associated with the variable in a class file, no compiler error is generated.
A subtle but important distinction to bear in mind is that the parameter variableString
is a string, not a variable name. If you pass an existing variable name as the first parameter to set()
without enclosing the name in quotation marks (""), the variable is evaluated before the value of expression
is assigned to it. For example, if you create a string variable named myVariable
and assign it the value "Tuesday," and then forget to use quotation marks, you will inadvertently create a new variable named Tuesday
that contains the value you intended to assign to myVariable
:
var myVariable:String = "Tuesday"; set (myVariable, "Saturday"); trace(myVariable); // outputs Tuesday trace(Tuesday); // outputs Saturday
You can avoid this situation by using quotation marks (""):
set ("myVariable", "Saturday"); trace(myVariable); //outputs Saturday
variableString:String —
A string that names a variable to hold the value of the expression parameter.
|
"Jakob"
to the name
variable. set("name", "Jakob"); trace(name);
The following code loops three times and creates three new variables, called caption0
,
caption1
, and caption2
:
for (var i = 0; i < 3; i++) { set("caption" + i, "this is caption " + i); } trace(caption0); trace(caption1); trace(caption2);
See also
static | keyword |
class someClassName{ static var name; static function name() { // your statements here } } |
Language version: | ActionScript 2.0 — To use this keyword, you must specify ActionScript 2.0 or later and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel. |
Player version: | Flash Player 6 |
Specifies that a variable or function is created only once per class rather than being created in every object based on that class.
You can access a static class member without creating an instance of the class by using the syntax someClassName.name
. If you do create an instance of the class, you can also access a static member using the instance, but only through a non-static function that accesses the static member.
You can use this keyword in class definitions only, not in interface definitions.
Parametersname:String —
The name of the variable or function that you want to specify as static.
|
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 AS 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; } }
Create a FLA or AS document in the same directory, and enter the following ActionScript in Frame 1 of the Timeline:
trace(Users.instances); var user1:Users = new Users(); trace(Users.instances); var user2:Users = new Users(); trace(Users.instances);
See also
super | statement |
super.method([arg1, ..., argN]) super([arg1, ..., argN]) |
Player version: | Flash Player 6 |
the first syntax style may be used within the body of an object method to invoke the superclass version of a method, and can optionally pass parameters (arg1 ... argN)
to the superclass method. This is useful for creating subclass methods that add additional behavior to superclass methods, but also invoke the superclass methods to perform their original behavior.
The second syntax style may be used within the body of a constructor function to invoke the superclass version of the constructor function and may optionally pass it parameters. This is useful for creating a subclass that performs additional initialization, but also invokes the superclass constructor to perform superclass initialization.
Parametersmethod:Function —
The method to invoke in the superclass.
|
|
argN —
Optional parameters that are passed to the superclass version of the method (syntax 1) or to the constructor function of the superclass (syntax 2).
|
Void — Both forms invoke a function. The function may return any value. |
switch | statement |
switch (expression){ caseClause: [defaultClause:] } |
Player version: | Flash Player 4 |
Creates a branching structure for ActionScript statements. As with the if
statement, the switch
statement tests a condition and executes statements if the condition returns a value oftrue
. All switch statements should include a default case. The default case should include a break statement that prevents a fall-through error if another case is added later. When a case falls through, it doesn't have a break statement.
expression —
Any expression.
|
String.fromCharCode(Key.getAscii())
parameter evaluates to A
, the trace
() statement that follows case "A"
executes; if the parameter evaluates to a
, the trace()
statement that follows case "a"
executes; and so on. If no case
expression matches the String.fromCharCode(Key.getAscii())
parameter, the trace()
statement that follows the default
keyword executes. var listenerObj:Object = new Object(); listenerObj.onKeyDown = function() { switch (String.fromCharCode(Key.getAscii())) { case "A" : trace("you pressed A"); break; case "a" : trace("you pressed a"); break; case "E" : case "e" : trace("you pressed E or e"); break; case "I" : case "i" : trace("you pressed I or i"); break; default : trace("you pressed some other key"); break; } }; Key.addListener(listenerObj);
See also
throw | statement |
throw expression |
Player version: | Flash Player 7 |
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:Object —
An ActionScript expression or object.
|
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");
The following code then calls the checkEmail()
function within a
try
code block. If the email_txt
string does not contain a valid e-mail address, the error message appears in a text field (error_txt
).
try { checkEmail("Joe Smith"); } catch (e) { error_txt.text = e.toString(); }
In the following example, a subclass of the Error class is thrown. The checkEmail()
function is modified to throw an instance of that subclass.
// Define Error subclass InvalidEmailError // In InvalidEmailError.as: class InvalidEmailAddress extends Error { var message = "Invalid email address."; }
In a FLA or AS file, enter the following ActionScript in Frame 1 of the Timeline:
import InvalidEmailAddress; function checkEmail(email:String) { if (email.indexOf("@") == -1) { throw new InvalidEmailAddress(); } } try { checkEmail("Joe Smith"); } catch (e) { this.createTextField("error_txt", this.getNextHighestDepth(), 0, 0, 100, 22); error_txt.autoSize = true; error_txt.text = e.toString(); }
See also
try..catch..finally | statement |
try { // ... try block ... } finally { // ... finally block ... } try { // ... try block ... } catch(error [:ErrorType1]) { // ... catch block ... } [catch(error[:ErrorTypeN]) { // ... catch block ... }] [finally { // ... finally block ... }] |
Player version: | Flash Player 7 |
Encloses a block of code in which an error can occur, and then respond to the error. If any code in the try
code block throws an error (using the throw
statement), control passes to the catch
block, if one exists, and then to the finally
code block, if one exists. The finally
block is always executed, regardless of whether an error was thrown. If code in the try
block doesn't throw an error (that is, if the try
block completes normally), then the code in the finally
block is still executed. The
finally
block is executed 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 necessary.
The error
parameter specified in a catch
handler must be a simple identifier such as e
or theException
or x
. The variable in a catch
handler can also be typed. When used with multiple catch
blocks, typed errors let you catch multiple types of errors thrown from a single try
block.
If the exception thrown is an object, the type matches 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 is not executed 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, then the ActionScript interpreter 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.
error:Object —
The expression thrown from a throw statement, typically an instance of the Error class or one of its subclasses.
|
The following example shows how to create a try..finally
statement. Because code in the
finally
block is guaranteed to be executed, it is typically used to perform any necessary clean-up after a
try
block is executed. In the following example, setInterval()
calls a function every 1000 millisecond (1 second). If an error occurs, an error is thrown and is caught by the catch
block. The finally block is always executed whether or not an error occurs. Because setInterval()
is used, clearInterval()
must be placed in the finally
block to ensure that the interval is cleared from memory:
myFunction = function () { trace("this is myFunction"); }; try { myInterval = setInterval(this, "myFunction", 1000); throw new Error("my error"); } catch (myError:Error) { trace("error caught: "+myError); } finally { clearInterval(myInterval); trace("error is cleared"); }
In the following example, the finally
block is used to delete an ActionScript object, regardless of whether or not an error occurred. Create a new AS file called Account.as:
class Account { var balance:Number = 1000; function getAccountInfo():Number { return (Math.round(Math.random() * 10) % 2); } }
In the same directory as Account.as, create a new AS or FLA document and enter the following ActionScript in Frame 1 of the Timeline:
import Account; var account:Account = new Account(); try { var returnVal = account.getAccountInfo(); if (returnVal != 0) { throw new Error("Error getting account information."); } } finally { if (account != null) { delete account; } }
The following example demonstrates a try..catch
statement. The code in the try
block is executed. If an exception is thrown by any code in the try
block, control passes to the catch
block, which shows the error message in a text field by using the Error.toString()
method.
In the same directory as Account.as, create a new FLA document and enter the following ActionScript in Frame 1 of the Timeline:
import Account; var account:Account = new Account(); try { var returnVal = account.getAccountInfo(); if (returnVal != 0) { throw new Error("Error getting account information."); } trace("success"); } catch (e) { this.createTextField("status_txt", this.getNextHighestDepth(), 0, 0, 100, 22); status_txt.autoSize = true; status_txt.text = e.toString(); }
The following example shows a try
code block with multiple, typed catch
code blocks. Depending on the type of error that occurred, the try
code block throws a different type of object. In this case,
myRecordSet
is an instance of a (hypothetical) class named RecordSet whose sortRows()
method can throw two types of errors, RecordSetException and MalformedRecord.
In the following example, the RecordSetException and MalformedRecord objects are subclasses of the Error class. Each is defined in its own AS class file.
// In RecordSetException.as: class RecordSetException extends Error { var message = "Record set exception occurred."; } // In MalformedRecord.as: class MalformedRecord extends Error { var message = "Malformed record exception occurred."; }
Within the RecordSet class's sortRows()
method, one of these previously defined error objects is thrown, depending on the type of exception that occurred. The following example shows how this code might look:
class RecordSet { function sortRows() { var returnVal:Number = randomNum(); if (returnVal == 1) { throw new RecordSetException(); } else if (returnVal == 2) { throw new MalformedRecord(); } } function randomNum():Number { return Math.round(Math.random() * 10) % 3; } }
Finally, in another AS file or FLA script, the following code invokes the sortRows()
method on an instance of the RecordSet class. It defines catch
blocks for each type of error that is thrown by sortRows()
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()); }
See also
var | statement |
var variableName [= value1][...,variableNameN[=valueN]] |
Player version: | Flash Player 5 |
Used to declare local variables. 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. More specifically, a variable defined using
If you declare variables outside a function, the variables are available througout the timeline containing the statement.var
is local to the code block containing it. Code blocks are demarcated by curly braces ({}).
You cannot declare a variable scoped to another object as a local variable.
my_array.length = 25; // ok var my_array.length = 25; // syntax error
When you use var
, you can strictly type the variable.
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";
var
when declaring properties inside class definitions in external scripts. Class files also support public, private, and static variable scopes.
variableName:String —
An identifier.
|
The following ActionScript creates a new array of product names. Array.push
adds an element onto the end of the array. If you want to use strict typing, it is essential that you use the var
keyword. Without var
before product_array
, you get errors when you try to use strict typing.
var product_array:Array = new Array("MX 2004", "Studio", "Dreamweaver", "Flash", "ColdFusion", "Contribute", "Breeze"); product_array.push("Flex"); trace(product_array); // output: MX 2004,Studio,Dreamweaver,Flash,ColdFusion,Contribute,Breeze,Flex
while | statement |
while(condition) { statement(s); } |
Player version: | Flash Player 4 |
Evaluates a condition and if the condition evaluates to true
, runs a statement or series of statements before looping back to evaluate the condition again. After the condition evaluates to false
, the statement or series of statements is 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 retested at the beginning of each iteration, as shown in the following steps:
condition
is evaluated.
condition
evaluates to true
or a value that converts to the Boolean value true
, such as a nonzero number, go to step 3.while
statement is completed and execution resumes at the next statement after the while
loop.statement(s)
.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 ({}
) used to enclose the block of 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 .
|
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
See also
with | statement |
with (object:Object) { statement(s); } |
Player version: | Flash Player 5 |
Lets you specify an object (such as a movie clip) with the object
parameter and evaluate expressions and actions inside that object with the statement(s)
parameter. This prevents you from having to repeatedly write the object's name or the path to the object.
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 the 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:
object
parameter in the innermost with
statement.object
parameter in the outermost with
statement. 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.
Instead of using with()
, you can use direct paths. If you find that paths are long and cumbersome to type, you can create a local variable and store the path in the variable, which you can then reuse in your code, as shown in the following ActionScript:
var shortcut = this._parent._parent.name_txt; shortcut.text = "Hank"; shortcut.autoSize = true;
object:Object —
An instance of an ActionScript object or movie clip.
|
_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); }
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