Buy this Book
Print Book $54.99 PDF $38.99 Read it Now!
Print Book £38.99
Add to UK Cart
Reprint Licensing

Essential ActionScript 3.0
Essential ActionScript 3.0

By Colin Moock
Book Price: $54.99 USD
£38.99 GBP
PDF Price: $38.99

Cover | Table of Contents


Table of Contents

Chapter 1: Core Concepts
A program is a set of written instructions to be executed (i.e., carried out) by a computer or a software application. The written, human-readable text of a program is called source code, or just code. The person who creates a program is called a programmer, a coder, or a developer. Every program is written in a particular programming language, just as every book is written in a particular language (English, Russian, Japanese, etc.). Programming languages dictate the syntax and grammar that programmers must use to form the instructions in a given program. This book provides from-the-ground-up coverage of the syntax, grammar, and usage of one specific programming language, ActionScript 3.0. Get ready for a good time.
ActionScript code is written in plain text, so an ActionScript program can be created with nothing more than a simple text editor, such as Notepad on Windows or TextEdit on Macintosh. However, most ActionScript programmers write ActionScript code using one (or both) of two commercial tools produced by Adobe Systems Incorporated: Flex Builder and the Flash authoring tool.
Flex Builder is an integrated development environment, or IDE. An IDE is an application for writing and managing code, much as a word processor is an application for creating printed documents. Developers use Flex Builder to create software applications and multimedia content using either ActionScript or MXML, or both. MXML is an XML-based language for describing user interfaces.
By contrast, the Flash authoring tool is a hybrid design, animation, and programming editor. Developers use the Flash authoring tool to create software applications and multimedia content by combining ActionScript code with manually drawn graphics, animation, and multimedia assets.
ActionScript 3.0 is supported by Flex Builder 2 or higher, and Flash CS3 (Version 9 of the Flash authoring tool) or higher. To obtain a copy of Flex Builder, visit . To obtain a copy of the Flash authoring tool, visit .
The vast majority of this book concentrates on the creation of software applications and multimedia content using pure ActionScript (i.e., code only). covers the use of ActionScript in the Flash authoring tool. This book specifically does not include coverage of MXML. For coverage of MXML, see O'Reilly's
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tools for Writing ActionScript Code
ActionScript code is written in plain text, so an ActionScript program can be created with nothing more than a simple text editor, such as Notepad on Windows or TextEdit on Macintosh. However, most ActionScript programmers write ActionScript code using one (or both) of two commercial tools produced by Adobe Systems Incorporated: Flex Builder and the Flash authoring tool.
Flex Builder is an integrated development environment, or IDE. An IDE is an application for writing and managing code, much as a word processor is an application for creating printed documents. Developers use Flex Builder to create software applications and multimedia content using either ActionScript or MXML, or both. MXML is an XML-based language for describing user interfaces.
By contrast, the Flash authoring tool is a hybrid design, animation, and programming editor. Developers use the Flash authoring tool to create software applications and multimedia content by combining ActionScript code with manually drawn graphics, animation, and multimedia assets.
ActionScript 3.0 is supported by Flex Builder 2 or higher, and Flash CS3 (Version 9 of the Flash authoring tool) or higher. To obtain a copy of Flex Builder, visit . To obtain a copy of the Flash authoring tool, visit .
The vast majority of this book concentrates on the creation of software applications and multimedia content using pure ActionScript (i.e., code only). covers the use of ActionScript in the Flash authoring tool. This book specifically does not include coverage of MXML. For coverage of MXML, see O'Reilly's Programming Flex 2 (Kazoun and Lott, 2007) and Adobe's Flex Builder documentation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Flash Client Runtime Environments
ActionScript programs can be executed by three different software applications (all produced by Adobe): Flash Player, Adobe AIR, and Flash Lite.
Flash Player executes ActionScript programs in a web browser or in a standalone mode on the desktop. Flash Player has very little access to the operating system (e.g., it cannot manage files, control windows, or access most hardware).
Adobe AIR executes ActionScript programs on the desktop and has full integration with the desktop operating system (e.g., can manage files, control windows, and access hardware).
Flash Lite executes ActionScript programs on mobile devices, such as cellular phones. As of the publication of this book, Flash Lite can execute ActionScript programs written in ActionScript 2.0, but not ActionScript 3.0, while Flash Player and Adobe AIR can execute programs written in ActionScript 3.0. Therefore, the techniques taught in this book apply to Flash Player and Adobe AIR, but will not apply to Flash Lite until it adds support for ActionScript 3.0.
In generic terms, Flash Player, Adobe AIR, and Flash Lite are all known as Flash client runtime environments (or Flash runtimes for short) because they manage ActionScript programs while they execute, or "run." Flash runtimes are available for Windows, Macintosh, and Linux, as well as a variety of different mobile hardware devices. Because ActionScript programs are executed by a Flash runtime, not a specific operating system or hardware device, each ActionScript program is considered portable because it can run on different hardware devices (phones, game consoles) and operating systems (Windows, Macintosh, and Linux).
In casual discussion, the term ActionScript virtual machine is sometimes used as an equivalent for Flash client runtime environment. There is, however, a difference between these two terms, so they should not be used interchangeably. The ActionScript virtual machine (AVM) is technically the software module inside Flash Player, Adobe AIR, and Flash Lite that executes ActionScript programs. But each Flash runtime also has other responsibilities, such as displaying content on screen, playing video and audio, and communicating with the operating system. The specific version of the ActionScript virtual machine that runs ActionScript 3.0 code is known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compilation
Before an ActionScript program can be executed by a Flash runtime, it must be converted from human-readable ActionScript 3.0 code to a condensed, binary format that Flash runtimes understand, known as ActionScript bytecode, or ABC. On its own, however, ActionScript bytecode cannot be executed by Flash runtimes; instead, it must be wrapped in a binary container file known as a .swf file. The .swf file stores the bytecode and any embedded media assets required by the ActionScript program in Flash file format, or SWF. The process of converting an ActionScript program to bytecode is known as compiling the program. The process of generating a .swf file is known as compiling the .swf file, or sometimes, exporting or publishing the .swf file.
To compile ActionScript 3.0 programs and .swf files, we use a software module known as a compiler. A compiler that compiles ActionScript code is known as an ActionScript compiler. A compiler that generates .swf files is known as a SWF compiler. Any SWF compiler that claims full support for the Flash file format includes an ActionScript compiler. Naturally, both Flex Builder 2 and the Flash authoring tool include a SWF compiler (and, by extension, an ActionScript compiler). Flex Builder 2 and the Flash authoring tool share the same ActionScript compiler but have different SWF compilers—known, respectively, as the Flex compiler and the Flash compiler. Adobe also offers the Flex compiler as a standalone command-line application called mxmlc. The mxmlc compiler is included in Adobe's free developer's toolkit, the Flex 2 SDK, available at .
When an ActionScript program runs, the Flash runtime reads compiled ActionScript bytecode and translates it into native machine-code instructions that are executed by the specific computer hardware on which the program is running. In many cases, the native machine-code instructions are saved so they can be used again without the need to be retranslated from ActionScript bytecode.
Just as converting ActionScript 3.0 code to bytecode is called compiling, the process of translating ActionScript bytecode into native machine code and then saving that machine code for later execution is, likewise, known as compiling. Hence, most ActionScript code undergoes two levels of compilation. First, the developer compiles the code from human-readable format to a format understood by the Flash runtime (ActionScript bytecode). Then, the Flash runtime automatically compiles the ActionScript bytecode to a format understood by the hardware running the program (native machine code). The latter form of compilation (bytecode to machine code) is known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Quick Review
The past several pages covered a lot of ground. Let's review what we've covered so far.
An ActionScript program is a set of instructions to be executed by one of the Flash runtimes: Flash Player, Adobe AIR, or Flash Lite. ActionScript programs can be written in a text editor, Flex Builder, or the Flash authoring tool. In order to run an ActionScript program, we must first compile it into a .swf file using a SWF compiler such as the Flash compiler included with the Flash authoring tool, or mxmlc, which is included with both Flex Builder 2 and the Flex 2 SDK.
Don't worry if some of the preceding concepts or terms are new to you. We'll be applying them abundantly over the next 900-plus pages.
Now let's write some code!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Classes and Objects
Imagine you are going to build an airplane, entirely from scratch. Think about the process you would follow. You very likely wouldn't just head to a metal shop and start welding. You'd have to draw up a blueprint for the airplane first. In fact, given that you are building the airplane from scratch, you'd have to draw up not just one, but many blueprints—one for each of the airplane's many parts (the wheels, the wings, the seats, the brakes, and so on). Each blueprint would describe a specific part conceptually and correspond to an actual part in the physical incarnation of the airplane. To build the airplane, you would manufacture each of the parts individually, and then assemble them according to a master blueprint. The interoperation of the airplane's assembled parts would produce the airplane's behavior.
If that all sounds logical to you, you've got what it takes to become an ActionScript programmer. Just as an airplane flying through the sky is a group of interoperating parts based on a set of blueprints, a running ActionScript program is a group of interoperating objects, based on a set of classes. ActionScript objects represent both the tangible things and the intangible concepts in a program. For example, an object might represent a number in a calculation, a clickable button in a user interface, a point in time on a calendar, or a blur effect on an image. Objects are incarnations, or instances, of classes. Classes are the blueprints upon which objects are based.
The first step in writing a new program is determining its classes. Each class describes, in code, both the characteristics and behavior of a particular type of object. Some of the classes in a program must be written from scratch, while others are provided by ActionScript and the various Flash runtimes. Classes written from scratch (known as custom classes) are used to produce specialized types of content, such as an order form for a shopping application, a car in a racing game, or a message in a chat application. By contrast, classes provided by ActionScript and the various Flash runtimes (known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Program
As we just learned, ActionScript programs are made up of classes, which are the blueprints for the interoperating parts (objects) of a program. Typically, the development of a new ActionScript program starts with a design phase, during which the program's functionality is broken into a logical set of classes. Each class is given a name, a set of features, and a role in the larger program. One class in particular is designated as the main class. The main class provides the starting point, or program point of entry, for the application. To start a new program, the Flash runtime automatically creates an instance of the program's main class.
For our virtual zoo example program, we'll name the main class VirtualZoo. As the first step in building the program, we'll create a folder on the filesystem, named virtualzoo. Within that folder, we'll create a subfolder named src (short for source) in which to store all .as files (i.e., all files containing source code).
Each program's main class code must be placed in a text file named after the main class, and given the extension .as. Accordingly, we'll create an empty text file named VirtualZoo.as. Notice that the filename VirtualZoo.as exactly matches the class name VirtualZoo and that case sensitivity matters. We'll place VirtualZoo.as in the folder virtualzoo/src. Here's the file structure for our program's source files so far:
virtualzoo
   |- src
      |- VirtualZoo.as
With VirtualZoo.as created, we can start writing the VirtualZoo class. However, first we must deal with a potential problem—if our chosen main class name conflicts with (i.e., is the same as) one of ActionScript's built-in classes, then ActionScript won't let us create the class, and our program won't be able to start. To prevent potential naming conflicts in our program, we use packages.
There is a lot of ground to cover, so we won't actually compile our zoo program's code until . If you decide to jump ahead and compile the examples presented in through , you are likely to encounter various warnings and errors. After , you'll be able to compile all versions of the example program without errors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Packages
Like its name suggests, a package is a conceptual container for a group of classes and, as we'll learn later, for other things in a program. Each package delimits an independent physical region of a program and gives that region a name, called the package name. By convention, package names typically start with a lowercase letter while class names typically start with an uppercase letter. This helps distinguish package names from class names.
When a class's source code resides within a package, that class automatically adopts the package's name as part of its own name, much like a child takes on his parents' family name. For example, a class named Player in a package named game becomes known as game.Player. Notice that the package name comes first and is separated from the class name using a period (.) character (character is simply programming jargon for letter, number, punctuation, and so on). The package name helps distinguish the game.Player class from other classes also named Player, thus preventing name conflicts between different parts of a program or between a program's custom classes and ActionScript's built-in classes.
To create a new package, we use a package definition directive. Let's dissect that term. In ActionScript, all program instructions are known generally as directives. Definitions are one type of directive; they create, or define something, such as a package or a class. In this case, the thing being defined is a package, hence the term, package definition directive.
A definition that creates something in a program is said to define or declare that thing. Definitions are sometimes also referred to as declarations.
Here's the general form of a package definition directive:
package packageName {
}
All package definitions start with a keyword: package. A keyword is a command name reserved for use by the ActionScript language. In this case, the package keyword tells ActionScript to create a package. After the package keyword, we provide the desired package name, represented by
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining a Class
To create a new class, we use a class definition, as shown in the following generalized code:
class Identifier {
}
A class definition starts with the keyword class, followed by a class name, represented by Identifier in the preceding code. The term identifier simply refers to a name. Identifiers must not contain spaces or dashes, and cannot start with a number. Class names conventionally use a capital letter for the first, and all subsequent words in the name, as in Date or TextField. (TextField is a built-in Flash-runtime class whose instances represent text that can be displayed on screen.)
The curly braces ({}) following Identifier in the preceding class definition are a block statement, just like the block statement in a package definition. A class definition's block statement is known as the class block or sometimes the class body. The class block contains directives that describe the characteristics and behavior of the class and its instances.
Here's the basic class definition for the main class of our simulated zoo game, VirtualZoo. We place the class definition in the package body, in the file VirtualZoo.as:
package zoo {
  class VirtualZoo {
  }
}
Because the preceding VirtualZoo class definition resides in a package named zoo, the complete name of the class (known as the fully qualified class name) is zoo.VirtualZoo. In casual discussion, however, we'll use the shorter, unqualified class name, VirtualZoo.
Now that we have our program's main class defined, let's create one of the other classes in the program—VirtualPet. From the VirtualPet class, we'll create objects representing pets in the zoo.
Like VirtualZoo, we'll place the source code for the VirtualPet class in the zoo package, in its own file named VirtualPet.as saved in the zoo folder. Here's the code from the VirtualPet.as file:
package zoo {
  class VirtualPet {
  }
}
Notice that a package definition can span multiple source files. Even though VirtualZoo and VirtualPet are stored in different
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Virtual Zoo Review
Our game now has two classes: VirtualZoo (the main class) and VirtualPet (which represents the pets in the game). The classes reside in the package zoo, and are stored in plain-text files named VirtualZoo.as and VirtualPet.as, respectively. By requirement of Adobe's ActionScript compilers, VirtualZoo is defined with the public attribute because it is the application's main class. By contrast, VirtualPet is defined with the internal attribute, so it can be used inside the zoo package only.
shows the code for our game so far. The example also introduces something new—code comments. A code comment is a note meant to be read by programmers only and is completely ignored by the compiler. ActionScript code comments come in two varieties: single line, which start with two slashes (//), and multiline, which start with the character sequence /*, and end with the character sequence */.
This is a single-line comment:
// No one here but us programmers
This is a multiline comment:
/*
No one here
but us programmers
*/
The current code for our zoo game follows.
Example 1-1. Zoo game
// Contents of the file VirtualZoo.as
package zoo {
  public class VirtualZoo {
  }
}

// Contents of the file VirtualPet.as
package zoo {
  internal class VirtualPet {
  }
}
Now let's carry on with the development of our program, starting with the constructor method of our main class, VirtualZoo.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constructor Methods
A constructor method (or, constructor, for short) is a discrete set of instructions used to initialize the instances of a class. To create a constructor method, we use a function definition within a class block, as shown in the following generalized code:
class SomeClass {
  function SomeClass (  ) {
  }
}
In the preceding code, the keyword function begins the constructor method. Next comes the constructor method name, which must exactly match the class name (case sensitivity matters!). The constructor method name is followed by a pair of parentheses that contain a list of constructor parameters, which we'll study later. The curly braces ({}) following the parameter list are a block statement, just like the block statements in package and class definitions. A constructor method's block statement is known as the constructor body. The constructor body contains the directives that initialize instances. Whenever a new instance of SomeClass is created, the directives in the constructor body are executed (sequentially, from top to bottom). Executing the directives in the constructor body is known as executing the constructor or, more casually, running the constructor.
Constructor methods are created using the function keyword because they are, technically speaking, a type of function. We'll study functions in .
When a class does not define a constructor function explicitly, ActionScript automatically provides a default constructor that performs no initialization on new instances of the class. Despite this convenience, as a best practice, always include a constructor, even if it is just an empty one. The empty constructor serves as a formal indication that the class design does not require a constructor and should be accompanied by a comment to that effect. For example:
class SomeClass {
  // Empty constructor. This class does not require initialization.
  function SomeClass (  ) {
  }
}
Unlike classes, the accessibility of constructor methods cannot be controlled with access-control modifiers. In ActionScript 3.0, all constructor methods are implicitly considered
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Objects
To create an object from a class (known technically as instantiating the object), we use the keyword new in combination with the name of the class. The following generalized code shows the approach:
new ClassName
For example, to make an object from our VirtualPet class, we use the following code:
new VirtualPet
Multiple independent objects can be made from the same class. For example, the following code creates two VirtualPet objects:
new VirtualPet
new VirtualPet
We've just learned that the generalized syntax for creating a new object is:
new ClassName
That syntax applies to both built-in and custom classes. For example, the following code creates a new instance of the built-in Date class, which represents a particular point in time:
new Date
However, for some native classes, ActionScript also offers an alternative, more convenient means of creating instances, known as literal syntax. For example, to create a new Number instance representing the floating-point number 25.4, we can use the convenient literal form:
25.4
Likewise, to create a new String instance representing the text "hello," we can use the convenient literal form:
"hello"
Finally, to create a new Boolean instance representing the logical state of true, we can use the convenient literal form:
true
And to create a new Boolean instance representing the logical state of false, we can use the convenient literal form:
false
Literal syntax is also available for the Object, Function, RegExp, and XML classes. We'll study Object literal syntax in , Function literal syntax in , and XML literal syntax in . For information on RegExp literal syntax, see Adobe's documentation.
Now that we know how to create objects, we can add a VirtualPet object to our zoo program. The following code does just that:
package zoo {
  public class VirtualZoo {
    public function VirtualZoo (  ) {
      
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables and Values
In ActionScript, every object is considered a single, self-contained piece of data (i.e., information) known as a value. Apart from objects, the only other legal values in ActionScript are the special values null and undefined, which represent the concept of "no value." A variable is an identifier (i.e., a name) associated with a value. For example, a variable might be the identifier submitBtn associated with an object representing a button in an online form. Or a variable might be the identifier productDescription associated with a String object that describes some product.
Variables are used to keep track of information in a program. They give us a means of referring to an object after it is created.
Variables come in four varieties: local variables, instance variables, dynamic instance variables, and static variables. We'll study the first two varieties now, and the remaining two varieties later in this book.
Local variables are used to track information temporarily within the physical confines of a constructor method, an instance method, a static method, or a function. We haven't studied instance methods, static methods, or functions yet so for now we'll focus on local variables in constructor methods.
To create a local variable within a constructor method, we use a variable definition, as shown in the following generalized code. Notice that the definition starts with the keyword var and, by convention, ends in a semicolon, as do all directives that do not include a block statement. The semicolon indicates the end of the directive, much like the period at the end of a sentence in a natural language.
class SomeClass {
  public function SomeClass (  ) {
    var identifier = value;
  }
}
In the preceding code, identifier is the local variable's name, and value is the value associated with that variable. Together, the equals sign and the value are known as the variable initializer because they determine the initial value of the variable.
Associating a variable with a value is known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constructor Parameters and Arguments
A constructor parameter is special type of local variable that is created as part of a constructor-method definition. Unlike regular local variables, a constructor parameter's initial value can be (or in some cases, must be) supplied externally when a new object is instantiated.
Constructor parameters are not created with the keyword var. Instead, to create a constructor parameter, we simply provide the desired name and variable initializer within the parentheses of a constructor function definition, as shown in the following generalized code:
class SomeClass {
  function SomeClass (identifier = value) {
  }
}
In the preceding code, identifier is the name of a constructor parameter, and value is the parameter's initial value.
To create more than one parameter for a constructor method, we list multiple parameter names, separated by commas, as shown in the following generalized code (notice the line breaks, which are both legal and common):
class SomeClass {
  function SomeClass (identifier1 = value1,
                      identifier2 = value2,
                      identifier3 = value3) {
  }
}
By default, the initial value of a constructor parameter is set to the value supplied in that parameter's definition. However, a constructor parameter's value can alternatively be supplied when an object is instantiated, using the following generalized object-creation code:
new SomeClass(value1, value2, value3)
In the preceding code, value1, value2, and value3 are values that are assigned, in order, to the constructor parameters of SomeClass's constructor method. A value supplied to a constructor parameter when an object is instantiated (as shown in the preceding code) is known as a constructor argument. Using a constructor argument to supply the value of a constructor parameter is known as passing that value to the constructor.
When a constructor parameter definition does not include a variable initializer, that parameter's initial value must be supplied via a constructor argument
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions
The written form of a value in an ActionScript program is known as an expression. For example, the following code shows a new expression—an expression representing a new object (in this case, a Date object):
new Date(  )
Likewise, the following code shows a literal expression representing a Number object with the value 2.5:
2.5
Individual expressions can be combined together with operators to create a compound expression, whose value is calculated when the program runs. An operator is a built-in command that combines, manipulates, or transforms values (which are known as the operator's operands). Each operator is written using either a symbol, such as +, or a keyword, such as instanceof.
For example, the multiplication operator, which multiplies two numbers, is written using the asterisk symbol (*). The following code shows a compound expression that multiplies 4 and 2.5:
4 * 2.5
When the preceding code is executed, ActionScript calculates the result of multiplying 4 by 2.5, and the entire compound expression (4 * 2.5) is replaced by that single calculated result (10). Calculating the value of an expression is known as evaluating the expression.
For a complete list of ActionScript operators, see .
To represent values that are not known when a program is compiled (at compile-time), but are supplied or calculated when the program runs (i.e., at runtime), we use variable names. When ActionScript evaluates an expression containing a variable name, it replaces that variable name with the corresponding variable's value. The process of replacing the variable name with the variable's value is known as retrieving, getting, or reading the variable value.
For example, consider the following compound expression, in which two values represented by variable names are multiplied together:
quantity * price
The variables quantity and price are placeholders for values that will be determined at runtime. The value of quantity might be, say, a number supplied by the user, while the value of
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Assigning One Variable's Value to Another
When we last saw our virtual zoo program, we had just finished creating a constructor method for the VirtualPet class. The constructor method defined a single parameter, name, whose value was supplied externally by object-creation code in the VirtualZoo class. Here's the code for the VirtualPet and VirtualZoo classes, as we left them:
// VirtualPet class
package zoo {
  internal class VirtualPet {
    internal var petName = "Unnamed Pet";

    public function VirtualPet (name) {
    }
  }
}

// VirtualZoo class
package zoo {
  public class VirtualZoo {
    public function VirtualZoo (  ) {
      var pet = new VirtualPet("Stan");
    }
  }
}
Now that we know how to use variables in expressions, we can use the name parameter to assign the value "Stan" to the new VirtualPet object's petName instance variable.
Recall that to assign an instance variable a new value, we use the following generalized code:
object.instanceVariable = value
According to that generalized code, we need to start our variable assignment by referring to an object. In this case, that object is the new VirtualPet instance being created. To refer to it, we use the keyword this, which is an automatically created parameter whose value is the object being created:
this
Within the body of a constructor method, the object being created is known as the current object. To refer to the current object, we use the keyword this.
After the keyword this, we write a dot, followed by the name of the instance variable whose value we wish to assign—in this case petName.
this.petName
Finally, we write an equals sign, then the value we wish to assign to the instance variable:
this.petName = value
The value we wish to assign is the value associated with the name parameter. Hence, for value, we write simply: name.
this.petName = name
At runtime, ActionScript replaces name, in the preceding code, with the value passed to the VirtualPet constructor. That value is then assigned to the instance variable
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
An Instance Variable for Our Pet
Earlier, we learned that a local variable expires when the method or function in which it is defined finishes executing. To make sure that the VirtualPet instance in our VirtualZoo class will be accessible after the VirtualZoo constructor finishes, let's update the VirtualZoo class. Instead of assigning our VirtualPet object to a local variable, we'll assign it to an instance variable, pet. We'll make pet private so that it can be accessed by code in the VirtualZoo class only. Here's the code (the new instance variable is shown in bold):
package zoo {
  public class VirtualZoo {
    private var pet;

    public function VirtualZoo (  ) {
      this.pet = new VirtualPet("Stan");
    }
  }
}
Over the preceding several sections, we've learned how to use instance variables to give characteristics to the objects of a class. Now let's explore how to use instance methods to give behaviors to the objects of a class.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Instance Methods
An instance method is a discrete set of instructions that carry out some task related to a given object. Conceptually, instance methods define the things an object can do. For example, the built-in Sound class (whose instances represent sounds in a program) defines an instance method named play that can start a sound playing. Likewise, the built-in TextField class (whose instances represent onscreen text) defines a method named setSelection that can change the amount of text selected in the text field.
To create an instance method, we use a function definition within a class block, as shown in the following generalized code:
class SomeClass {
  function identifier (  ) {
  }
}
In the preceding code, the keyword function begins the instance method. Next comes the instance method name, which can be any legal identifier. (Recall that identifiers must not contain spaces or dashes, and cannot start with a number.) The method name is followed by a pair of parentheses that contain a list of method parameters, which we'll study later. The curly braces ({}) following the parameter list are a block statement. A instance method's block statement is known as the method body. The method body contains directives that perform some task.
Instance methods are created using the function keyword because they are, technically speaking, a type of function. We'll study functions in .
To execute the code in a given method body, we use a call expression, as shown in the following generalized code. Notice the important and mandatory use of the parentheses operator, ( ), following the method name.
object.methodName(  )
In the preceding code, methodName is the name of the method whose code should be executed, and object is a reference to the specific instance that will conceptually perform the task represented by the specified method. Using a call expression to execute the code in an instance method's body is known as calling a method of an object (or, synonymously calling a method through an object
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Members and Properties
In the ActionScript 3.0 specification, an object's variables and methods are referred to collectively as its properties, where property means "a name associated with a value or method." Confusingly, in other ActionScript documentation (most notably Adobe's ActionScript Language Reference), the term property is also used to mean "instance variable." To avoid the confusion caused by this contradiction, this book avoids the use of the term "property" entirely.
Where necessary, this book uses the traditional object-oriented programming term instance members (or simply members) to refer to a class's instance methods and instance variables collectively. For example, we might say "radius is not a member of Box," meaning that the Box class does not define any methods or variables named radius.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Virtual Zoo Review
This chapter has introduced a large number of concepts and terms. Let's practice using them by reviewing our virtual zoo program for the last time in this chapter.
Our virtual zoo game has two classes: VirtualZoo (the main class) and VirtualPet (which represents the pets in the zoo).
When our program starts, the Flash runtime automatically creates an instance of VirtualZoo (because VirtualZoo is the application's main class). The act of creating the VirtualZoo instance causes the VirtualZoo constructor method to execute. The VirtualZoo constructor method creates an instance of the VirtualPet class, with a single constructor argument, "Stan."
The VirtualPet class defines three instance variables, petName, currentCalories, and creationTime. Those three instance variables represent the following pet characteristics: the pet's nickname, the amount of food in the pet's stomach, and the pet's birth date. For a new VirtualPet object, the initial value of currentCalories is a number created using the literal expression 1000. The initial value of creationTime is a Date object representing the time at which each VirtualPet object is created. When a VirtualPet object is created, petName is assigned the value of the required constructor parameter, name. The constructor parameter name receives its value through a constructor argument, supplied by the new expression that creates the VirtualPet object.
The VirtualPet class defines two instance methods, eat( ) and getAge( ). The eat( ) method increases currentCalories by the specified numeric value. The getAge( ) method calculates and returns the pet's current age, in milliseconds.
displays the current code for our zoo program.
Example 1-2. Zoo program
// VirtualPet class
package zoo {
  internal class VirtualPet {
    internal var petName;
    private var currentCalories = 1000;
    private var creationTime;

    public function VirtualPet (name) {
      this.creationTime = new Date(  );
      this.petName = name;
    }

    public function eat (numberOfCalories) {
      this.currentCalories += numberOfCalories;
    }

    public function getAge (  ) {
      var currentTime = new Date(  );
      var age = currentTime.time - this.creationTime.time;
      return age;
    }
  }
}

// VirtualZoo class
package zoo {
  public class VirtualZoo {
    private var pet;

    public function VirtualZoo (  ) {
      this.pet = new VirtualPet("Stan");
    }
  }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Break Time!
We've made great progress in this chapter. There's lots more to learn, but it's time for a well-deserved break. When you're ready for more ActionScript 3.0 essentials, head on to the next chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Conditionals and Loops
In this chapter, we'll depart from the general topics of classes and objects. Instead, we'll focus, on two essential types of statements: conditionals and loops. Conditionals are used to add logic to a program, while loops are used to perform repetitive tasks. Both conditionals and loops are extremely common, and can be found in nearly every ActionScript program. Once we've finished with conditionals and loops, we'll return to classes and objects, and continue developing our virtual zoo program.
This chapter presents all code examples outside the context of a functioning class or program. However, in a real program, conditionals and loops can be used within instance methods, constructor methods, static methods, functions, directly within class bodies or package bodies, and even outside package bodies.
A conditional is a type of statement that executes only when a specified condition is met. Conditionals let a program choose between multiple possible courses of action based on the current circumstances.
ActionScript provides two different conditionals: the if statement and the switch statement. ActionScript also provides a single conditional operator, ?:, which is covered briefly in . For details on the ?: operator, see Adobe's ActionScript language reference.
The if statement is like a two-pronged fork in the road. It contains two blocks of code and an expression (known as the test expression) that governs which block should execute. To create an if statement, we use the following generalized code:
if (testExpression) {
  codeBlock1
} else {
  codeBlock2
}
When ActionScript encounters an if statement, it executes either codeBlock1 or codeBlock2, depending on the value of testExpression. If the value of testExpression is the Boolean value true, then the first block is executed. If the value of testExpression is the Boolean value false, then the second block is executed. If the value of testExpression is not a Boolean value, ActionScript automatically converts
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditionals
A conditional is a type of statement that executes only when a specified condition is met. Conditionals let a program choose between multiple possible courses of action based on the current circumstances.
ActionScript provides two different conditionals: the if statement and the switch statement. ActionScript also provides a single conditional operator, ?:, which is covered briefly in . For details on the ?: operator, see Adobe's ActionScript language reference.
The if statement is like a two-pronged fork in the road. It contains two blocks of code and an expression (known as the test expression) that governs which block should execute. To create an if statement, we use the following generalized code:
if (testExpression) {
  codeBlock1
} else {
  codeBlock2
}
When ActionScript encounters an if statement, it executes either codeBlock1 or codeBlock2, depending on the value of testExpression. If the value of testExpression is the Boolean value true, then the first block is executed. If the value of testExpression is the Boolean value false, then the second block is executed. If the value of testExpression is not a Boolean value, ActionScript automatically converts testExpression to a Boolean object and uses the result of that conversion to decide which block to execute. (The rules for converting a value to the Boolean class are described in in Chapter 8.)
For example, in the following if statement, the supplied test expression is the Boolean value true, so the value of the variable greeting is set to "Hello", not "Bonjour".
var greeting;

// Test expression is true, so...
if (true) {
  // ...this code runs
  greeting = "Hello";
} else {
  // This code doesn't run
  greeting = "Bonjour";
}
Of course, the preceding test expression would rarely, if ever, be used in a real program because it always produces the same result. In the vast majority of cases, the test expression's value is dynamically determined at runtime based on information calculated by the program or provided by the user.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Loops
In the preceding section, we saw that a conditional causes a statement block to execute once if the value of its test expression is true. A loop, on the other hand, causes a statement block to be executed repeatedly, for as long as its test expression remains true.
ActionScript provides five different types of loops: while, do-while, for, for-in, and for-each-in. The first three types have very similar effects but with varying syntax. The remaining two types are used to access the dynamic instance variables of an object. We haven't studied dynamic instance variables yet, so for now we'll consider the first three types of loops. For information on for-in and for-each-in, see .
Structurally, a while statement is constructed much like an if statement: a main statement encloses a code block that is executed only when a given test expression is true:
while (testExpression) {
  codeBlock
}
If testExpression is true, the code in codeBlock (called the loop body) is executed. But, unlike the if statement, when the codeBlock is finished, execution begins again at the beginning of the while statement (that is, ActionScript "loops" back to the beginning of the while statement). The second pass through the while statement works just like the first: the testExpression is evaluated, and if it is still true, codeBlock is executed again. This process continues until testExpression becomes false, at which point execution continues with any statements that follow the while statement in the program. If testExpression never yields false, the loop executes infinitely, eventually causing the Flash runtime to generate an error, which stops the loop (and all currently executing code). To avoid infinite execution, a while loop's codeBlock typically includes a statement that modifies the testExpression, causing it to yield false when some condition is met.
For example, consider the following loop, which calculates 2 to the power of 3 (i.e., 2 times 2 times 2) by executing the loop body two times:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Boolean Logic
Early in this chapter, we saw how to make logical decisions using test expressions that yield Boolean values. The decisions were based on a single factor, such as "if language is "english", then display "Hello". But not all programming logic is so simple. Programs often need to consider multiple factors in branching logic (i.e., decision making). To manage multiple factors in a test expression, we use the Boolean operators: || (logical OR) and && (logical AND).
The logical OR operator is most commonly used to initiate some action when at least one of two conditions is met. For example, "If I am hungry or I am thirsty, I'll go to the kitchen." The symbol for logical OR is made using two "pipe" characters: ||. Typically, the pipe character (|) is accessible using the Shift key and the Backslash (\) key in the upper right of most Western keyboards, where it may be depicted as a dashed vertical line. Logical OR has the following general form:
expression1 || expression2
When both expression1 and