JETZT ONLINE BESTELLEN
Add to Cart
Essential ActionScript 3.0

First Edition Juni 2007
ISBN 978-0-596-52694-8
946 Seiten
EUR53.00, SFR87.90

Weitere Informationen zu diesem Buch

Inhaltsverzeichnis | Index | Rezensionen |


Inhaltsverzeichnis

	
Chapter 1: Core Concepts
Inhaltsvorschau
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 http://www.adobe.com/products/flex/productinfo/overview/. To obtain a copy of the Flash authoring tool, visit http://www.adobe.com/go/flash/.
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
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Tools for Writing ActionScript Code
Inhaltsvorschau
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 http://www.adobe.com/products/flex/productinfo/overview/. To obtain a copy of the Flash authoring tool, visit http://www.adobe.com/go/flash/.
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.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Flash Client Runtime Environments
Inhaltsvorschau
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
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Compilation
Inhaltsvorschau
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 http://www.adobe.com/go/flex2_sdk.
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
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Quick Review
Inhaltsvorschau
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!
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Classes and Objects
Inhaltsvorschau
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
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Creating a Program
Inhaltsvorschau
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.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Packages
Inhaltsvorschau
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:
packagepackageName {

}
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 packageName in the preceding code. (Throughout this book, italicized code, such as
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Defining a Class
Inhaltsvorschau
To create a new class, we use a class definition, as shown in the following generalized code:
classIdentifier {

}
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 .as files, they belong to the same package, zoo. Any class in any file that resides in a package named zoo is considered part of the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Virtual Zoo Review
Inhaltsvorschau
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.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Constructor Methods
Inhaltsvorschau
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:
classSomeClass {

  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:
classSomeClass {

  // 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 public. (Future versions of ActionScript might, however, allow for non-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Creating Objects
Inhaltsvorschau
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:
newClassName
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:
newClassName
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 (  ) {new VirtualPet

    }

  }

}
Notice that the preceding code refers to the VirtualPet class by its unqualified name, VirtualPet—not by its qualified name, zoo.VirtualPet. Code in a given package can refer to the classes in that package by their unqualified names.
By contrast, code in a given package cannot refer to classes in other packages at all. To gain access to a public class in another package, we use the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Variables and Values
Inhaltsvorschau
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.
classSomeClass {

  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 assigning, setting, or writing the variable's value.
When the variable initializer is omitted, ActionScript automatically assigns the variable a default value. Default values for variables are discussed in .
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Constructor Parameters and Arguments
Inhaltsvorschau
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:
classSomeClass {

  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):
classSomeClass {

  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:
newSomeClass(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. Such a parameter is known as a required constructor parameter. The following generalized code shows how to create a class with a single required constructor parameter (notice that the parameter definition does not include a variable initializer):
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Expressions
Inhaltsvorschau
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 price might be a number retrieved from a database. For the sake of this example, let's assume that the variable
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Assigning One Variable's Value to Another
Inhaltsvorschau
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 PetVirtualPet (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 petName.
Here's the assignment code as it appears in our VirtualPet constructor:
package zoo {

  internal class VirtualPet {

    internal var petName = "Unnamed Pet";



    public function VirtualPet (name) {
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
An Instance Variable for Our Pet

Themen

Buchreihen

Special Interest

International Sites

O'Reilly China O'Reilly USA O'Reilly Japan O'Reilly Taiwan