OReilly Essential ActionScript 2 0 Jun 2004 ISBN 0596006527


2 months ago
Full text

• Table of Contents • Index • Reviews • Reader Reviews • Errata • Academic

  For more information, contact our corporate/institutional sales department: (800)998-9938 or corporate@oreilly.com . In Chapter 12 and Chapter 13 , you'll learn how user interface components and movie clips fit into a well-structured Flash application.

Chapter 14 , you'll see how

  After an introduction to design patternsin Chapter 15 , we'll explore four common patterns in Chapter 16 through patterns presented in Part III, you'll have confidence consulting the larger body of patterns available online and in otherliterature. Specifically, you won't find much discussion of companion technologies, such as Flash Remotingor Flash Communication Server, nor will you find a dictionary- style Language Reference, as you do in ActionScript for Flash MX: The Definitive Guide (O'Reilly).

Chapter 1 introduces ActionScript 2.0 in more detail, but this

  You may ask, "Is this book aboutActionScript 2.0 syntax, object-oriented design, or object- oriented programming?" The answer is, "All of the above."For more information about ActionScript 2.0 and ActionScript1.0 in relation to Flash Player 6 and Flash Player 7, see Chapter 1 . Copyright 2004 O'Reilly Media, Inc., 0-596-00652-7"If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com .

Chapter 10 . The following keen beta

  Special thanks to Mark Jonkman and Nick Reader for their consistently thorough examinations of the manuscript. Colin MoockToronto, CanadaMarch 2004 Part I: The ActionScript 2.0 Language Part I teaches you the fundamentals of object-oriented concepts, syntax, and usage in ActionScript 2.0.

Chapter 1. ActionScript 2.0 Overview Over the course of this book, we'll study ActionScript 2.0 and

  There's lots to learn ahead but, before we get into too much detail, let'sstart with a quick summary of ActionScript 2.0's core features and Flash Player 7's new capabilities. If you have anActionScript 1.0 background, the summary will give you a general sense of what's changed in the language.

1.1 ActionScript 2.0 Features

  See Chapter 4 . See Chapter 4 .

Chapter 4 . The private and public keywords, used to prevent certain

  methods and properties from being accessed outside of a class. Static typing for variables, properties, parameters, and return values, used to declare the datatype for each item.

Chapter 3 for details on type mismatch errors. Type casting, used to tell the compiler to treat an object as

Chapter 3 for details on casting. Classpaths, used to define the location of one or more

  See Chapter 10 . See Chapter 13 .

1.2 Features Introduced by Flash Player 7

  (For information on export formats, see "Setting a Movie's ActionScript Version andPlayer Version," later in this chapter.) Although these features are not the direct topic of study in this book, we'll cover a fewof them during our exploration of ActionScript 2.0. As such, the preceding Flash Player features are not all covered ina detailed manner.

1.3 Flash MX 2004 Version 2 Components

  Flash MX introduced componentsready-to-use interface widgets and code modules that implement commonly neededfunctionality. Flash's built-in components make it relatively easy to create desktop-style Flash applications.

Chapter 12 for

  Officially, the v2 components require FlashPlayer or higher; however, tests show that many v2 components work in earlier releases of Flash Player 6(especially Flash Player and higher). The v1 component update for ActionScript 2.0 is available at the Flash Exchange ( http://www.macromedia.com/exchange/flash ), in the UserInterface category, under the title "Flash MX Components for Flash MX 2004." Do not mix ActionScript 1.0 OOP techniques with ActionScript 2.0 code.

Chapter 12 , we'll learn how to program graphical, OOP applications that use the v2 components

1.4 ActionScript 1.0 and 2.0 in Flash Player 6 and

7 ActionScript 1.0 is based on the ECMAScript 3 standard (as is

  For details see http://moock.org/asdg/technotes/crossDomainPolicyFiles . Runtime case sensitivity support by language, file format, and Flash Player versionMovie compiled as either ActionScript 1.0 Played in Flash Played in Flash or 2.0 and Player 6 Player 7[5] [5]Flash Player 6-format .swf file Case insensitive [6] Case-insensitive Flash Player 7-format .swf file Not supported Case-sensitiveas "if" are case sensitive, even in Flash Player 6.

1.4.2 Changes to ActionScript 1.0 in Flash Player

7 In a Flash Player -format .swf file running in Flash Player

  Specifically: The value undefined converts to the number NaN when used in a numeric context and to the string "undefined"when used in a string context (in Flash Player 6, undefined Identifiers (function names, variable names, property names, etc.) are case sensitive. For example, the identifiers firstName and firstname refer to two different variables in Flash Player 7.

1.4.3 Flash 4 Slash Syntax Is Not Supported in ActionScript 2.0

In Flash 4 and subsequent versions, variables could be referenced with so-called "slash syntax." For example, in Flash4, the following code is a reference to the variable x on the movie clip ball : /ball:x That syntax generates the following error if you attempt to use it with the ActionScript 2.0 compiler, whether exporting in FlashPlayer 6 or Flash Player 7 format: Unexpected '/' encountered

1.5 Let's Go OOP

Now that we've had a taste of what ActionScript 2.0 has to offer, we can start our study of object-oriented programmingwith Flash in earnest. When you're ready to get your hands dirty, move on to

Chapter 2. Object-Oriented ActionScript Ironically, Flash users who are new to object-oriented

  programming (OOP) are often familiar with many object- oriented concepts without knowing their formal names. Thischapter demystifies some of the terminology and brings newer programmers up to speed on key OOP concepts.

2.1 Procedural Programming and Object- Oriented Programming

  The program runs by executing functions and changing variablevalues, typically for the purpose of handling input and generating output. Procedural programming is sensible forcertain applications; however, as applications become larger or more complex and the interactions between procedures (andthe programmers who use them) become more numerous, procedural programs can become unwieldy.

2.2 Key Object-Oriented Programming Concepts

  For example, an OOP space fighting game might have 20 individual SpaceShip objects on screen at one time, all created from a single SpaceShip class. For example, the phrases "Make a new SpaceShip instance" and "Make a newSpaceShip object" mean the same thing.

2.2.1 Class Syntax

  } } Notice how the SpaceShip class groups related aspects of the program neatly together (as do all classes). Variables(properties), such as speed and damage , related to spaceships are grouped with functions (methods) used to move a spaceshipand fire its weapons.

2.2.2 Object Creation

  Objects are created (instantiated) with the new operator, as in: new ClassName( ) where ClassName is the name of the class from which the object will be created. For example, we might var ship:SpaceShip = new SpaceShip( ); Each object is a discrete data value that can be stored in a variable, an array element, or even a property of anotherobject.

2.2.3 Object Usage

  An object's methods provide its capabilities (i.e., behaviors)things like "fire missile," "move," and "scroll down."An object's properties store its data, which describes its state at any given point in time. For example, at a particular point in agame, our ship 's current state might be speed is 300, damage is 14.

Chapter 4 , methods and properties should be defined as public only if they must be accessed externally. To invoke a method, we use the dot operator (i.e., a period) and

  For example: // Invoke the ship object's fireMissile( ) method. For example: // Set the ship's speed property to 120.

2.2.4 Encapsulation

  Objects are said to encapsulate their property values and method source code from the rest of the program. If properlydesigned, an object's private properties and the internal code used in its methods (including public methods) are its ownbusiness; they can change without necessitating changes in the rest of the program.

Chapter 4 , we'll learn how to use the private modifier to

prevent a method or property from being accessed by other parts of a program.

2.2.5 Datatypes

  For example, by specifying that the datatype of speed is a number,we prevent someone from unintentionally setting speed to, say, the string "very fast." The following code generates a compile-time error due to the datatype mismatch: public var speed:Number = "very fast"; // Error! We'll talk more about datatypes and type mismatches in Chapter 3 .

2.2.6 Inheritance

  inheritance to allow one class to adopt the method and property definitions of another. For example, specific Car, Boat, and Plane classes could reuse the features of a generic Vehicle class, thus reducing redundancy in the application.

2.2.7 Packages

  We'll learn about Player-generated runtime errors and program-generated runtime errors in Chapter 10 . We'll study more complex ways to structure and run object- oriented Flash applications in Chapter 5 , Chapter 11 , and Chapter 12 .

2.3 But How Do I Apply OOP?

  (In fact, we'll do just that in Chapter 5 and Chapter 7 !) So if Flash supports both procedural and object-oriented programming, how much of each is right for your project? If you suspect that your highly customized UI will be used formore than a single project, you should strongly consider developing it as a reusable class library or set of componentswith OOP.

2.4 On with the Show!

  We're now ready to move on with the rest of Part I, where we'll study all of those concepts again in detail, applyingthem to practical situations along the way. If you're already quite comfortable with OOP and want to dive into someexamples, see Chapter 5 , Chapter 7 , Chapter 11 , and Chapter 12 , and all of Part III, which contain in-depth studies of real- world object-oriented code.

Chapter 3. Datatypes and Type Checking ActionScript 2.0 defines a wide variety of datatypes. Some

  The compiler, hence, allows any type of data to be stored in today . The preceding code simply stores the return value of getDay( ) into today .

Chapter 4 for related

  And you could access a nonexistent method or property without errors: // ActionScript 1.0 code...var s = new Sound( ); s.thisMethodDoesntExist( ); // No error in ActionScript 1.0! Hence, to cause the preceding ActionScript1.0 code to generate helpful errors in ActionScript 2.0, we declare the variables' datatypes, as follows: // ActionScript 2.0 code...var x:Number = 10; // Here, x's datatype starts as Number x = "hello world"; // This attempt to store a string invar s:Sound = new Sound( ); s.thisMethodDoesntExist( ); // ERROR!

3.1 Why Static Typing?

  CodeUnitTestFirstExampleTwo . For an ActionScript 2.0 unit testing tool, see http://www.as2unit.org .

3.2 Type Syntax

  ActionScript 2.0's compile-time type checking can be applied to: A variableA propertyA function or method parameterA function or method return value To enable type checking for any of the preceding items, we declare the item's type using post-colon syntax, as discussedearlier and in the next section. Armed with thatknowledge, the compiler can warn us of two possible error conditions: If a value of an incompatible type is stored in a variable, passed as a function parameter, or returned by a function,the compiler generates a type mismatch error.

3.2.1 Declaring Variable and Property Datatypes

  To declare the datatype of a variable or property, use the following syntax: var variableOrPropertyName:datatype; where variableOrPropertyName is the name of the variable or property, and datatype is the type of data that the variable orproperty can legally contain. For example, this code attempts to assign a Number to currentTime , whose datatype was declared as Date:var currentTime:Date; currentTime = 10; That code yields the following compile-time error: Type mismatch in assignment statement: found Number where Date is required.

Chapter 4 , ActionScript 2.0 provides a special

  However, due to a bug in the ActionScript 2.0 compiler in FlashMX 2004, the following code does change the datatype of currentTime from Date to Number: var currentTime:Date;var currentTime:Number = 10; // Redeclare with assignment.currentTime = 11; // currentTime's datatype is now The preceding code redeclares the datatype of the variable currentTime and also reassigns its value. The reassignment for (var i:Number = 0; i < 10; i++) { trace(i);} // Second loop: reuse i, but don't include var or :Numberfor (i = 15; i > 0; i--) { trace(i);} In a loop in which a different datatype is required, use a new variable: // Use p instead of i.for (var p:String in someObj) { // List properties of an object.trace("Found property: " + p); } Naturally, local variables within one function have no relation to local variables within a separate function.

3.2.2 Declaring Method Parameter and Return Value Datatypes

  The following code shows how to declare the datatype of method or function parameters and return values: function methodName (param1Name:param1Type, param2Name:param2Type):returnType {// ...} where methodName is the name of the method or function, param1Name and param2Name are the names of the parameters, param1Type and param2Type are the parameters' datatypes, and returnType is the datatype of the function's return value. returnType .

Chapter 4 , we'll study method definition again, in much greater detail

3.2.3 Why Post-Colon Syntax?

  As we've learned in this section, ActionScript 2.0 uses the following, slightly unusual syntax for type declarations: variableOrPropertyName:datatype = value; By contrast, Java and C++ use: datatype variableName = value; In JavaScript 2.0: Evolving a Language for Evolving Systems,Waldemar Horwat (one of the creators of the ECMAScript 4 specification) explains the reason for this difference at http://www.mozilla.org/js/language/evolvingJS.pdf . There is no technical reason for using [post-colon] syntax, but it's too late to reverse itnow (implementations using this syntax have already shipped), even though most of the people involved with itadmit the syntax is a mistake.

3.3 Compatible Types

The following discussion assumes an understanding of inheritance in OOP. If you're not familiar with that concept, youmay want to skip this section for now and return to it once you've read

Chapter 6 . Earlier we learned that a variable of one type can store only a

  And we'll revisit our Basketball and Ball classes under"Polymorphism and Dynamic Binding" in Chapter 6 . We'll returnto subtypes and polymorphism in Chapter 6 .

3.3.1 Handling Any Datatype

  We can subsequently store an instance of any class in it without error: var container:Object = new Date( ); // No error.container = new Color( ); // No error. This technique works because the Object class is the superclass of all ActionScript classes, so all types are compatible with the Object type (primitive values such as the Boolean true or the string "hello world" are not, strictly speaking, instances of any var container:Object = new Date( ); // No error.trace(container.toString( )); // Execute toString( ) container.blahblahblah( ); // Invoke nonexistent method.

3.3.2 Compatibility with null and undefined

  Rest easyunlike other values, the null and function square (x:Number):Number { return x*x;} square(null); // Legal.function square (x:Number):Number { if (x == 0) {return null; // Legal.} return x*x;} Declaring something's type to be Object makes it a universal recipient, like a person with type AB positive blood who canaccept any type of blood you give her. On the other hand, null and undefined are universal donors, like people with type Onegative blood whose blood can be transfused into any other person without harm.

3.4 Built-in Dynamic Classes

  For example, the following codecreates a variable of type Array and attempts to place a Date instance into it: var list:Array = new Date( ); It yields the following error: Type mismatch in assignment statement: found Date where Array is required. Furthermore, ActionScript 1.0 allowed you to add new methods and properties to an entire class at runtime (viathe class's prototype object).

Chapter 6 , under

"Augmenting Built-in Classes and Objects."

3.5 Circumventing Type Checking

  For example, the following code creates a variable, x , butdoes not declare x 's datatype: var x = 10; Because the variable x is not typed, type checking is not(indeed cannot be) performed, and x 's datatype can be changed without generating an error: x = "hello"; // Change from Number to String. Furthermore, accessing nonexistent properties and methods on x causes no error: trace(x._width); // No error.

3.5.1 Creating Parameters That Accept Multiple Types

  Within the body of the function, we invoke toString( ) on whatever value was passed for msg :function output (msg:Object):Void { trace(msg.toString( ));} The toString( ) method is defined by the Object class, so it is guaranteed to work on any value passed for msg . For example, the following rewrite of the output( ) function checks the datatype of msg .

3.5.3 Bypassing Type Checking on a Per-Use Basis

  First, we can use the [] operator to access methods and properties without concern for compile-time type checking. But if we use the [] operator when referring to url , no error occurs, and a new url property is added to the song object: var song:Sound = new Sound( ); song["url"] = "track3.mp3";trace(song["url"]); // Displays: track3.mp3 This technique adds a new property (in this case, url ) to the object instance (in this case, song ), not to the class itself (inthis case, Sound).

Chapter 6 , under "Augmenting Built-in Classes and Objects." All we've done here is bypass some of the

  For example, the following code casts someValue to the TextField class so that it can be stored in the variable tf , whose type is TextField: var tf:TextField = TextField(someValue); In ActionScript 2.0, casting data to a datatype always succeeds at compile time. You may fool the compiler but, as we'll learn next, at runtime you can easily end up with a reference instead of the null object you thought you cast.

3.7 Datatype Information for Built-in Classes

  The following code generates an error because the TextFormat.align property requires a String, buta Boolean is used: var tf:TextFormat = new TextFormat( ); tf.align = true; // Error! Type information can also be retrieved from the source code of the classes in the installation folder for Flash MX 2004, asfollows: /Macromedia/Flash MX 2004/en/First Run/Classes Component class definitions are found in the /mx/ directory, one directory below the /Classes/ directory listed previously.

3.8 ActionScript 2.0 Type Checking Gotchas

  ActionScript 2.0's type checking system has its quirks and limitations. The remainder of this chapter covers someanomalies to keep in mind when working with ActionScript 2.0.

3.8.1 Global Variables Can't Be Typed

  To create a global variable in ActionScript, we add a property to the _global object, as follows: _global.varname = value; The preceding property-definition syntax is a carryover fromActionScript 1.0 and does not support datatype declarations. It is, therefore, impossible to use type checking with a globalvariable.

3.8.2 Type Checking and Timeline Code

  (Should be a type mismatch error.) Similarly, the following attempt to store a number returned by getBytesLoaded( ) in a String variable does not generate an error when the code is placed on a frame: // No error. (Should be a type mismatch error.) function square(x:Number):Number {return x * x; }square(this); // No error.

3.8.3 Type Checking XML Instances

  It creates a new XML instance, stores the instance in a variable, xmlDoc , then attempts to assign one of its child nodes to a new variable, xmlFragment : var xmlDoc:XML = new XML("<P>Hello world</P>");var xmlFragment:XML = xmlDoc.firstChild; // Error. To fix the error, we simply declare the datatype of xmlFragment as XMLNode instead of XML (change shown in bold): var xmlDoc:XML = new XML("<P>Hello world</P>"); var xmlFragment:XMLNode = xmlDoc.firstChild; // No error The preceding code does not cause a type mismatch error becauseas we learned earlier under "Compatible Types"thecompiler knows that every XML instance has, through XMLNode class despite their names, which might imply the opposite).

3.8.4 No Type Checking with the [] Operator

  No error occurs when the method is accessed via the [] operator: var d:Date = new Date( ); d["noSuchMethod"]( ); // No compile-time error, but fails// silently at runtime.d.noSuchMethod( ); // Compile-time error. No error occurs when the property is accessed via the [] operator: target_mc.createTextField("tf", 0, 0, 0, 400, 400);var name_txt:TextField = target_mc.tf; name_txt.border = true; Therefore, to take advantage of type checking, you should rewrite any old code that uses the [] operator to accessmethods or properties.

3.8.5 Array Elements and Type Checking

  For example, here we have an XML instance: var doc:XML = new XML("<P>hello world</P"); Suppose we store that XML instance in an array, like this: Because the array, items , does not keep track of the datatypes of its elements, the following code should generate a typemismatch error: var otherDoc:XML = items[0]; The programmer knows that the element items[0] is an XML instance, but the compiler doesn't recognize this fact. The sensible solution here is to cast the value to the XML items[0] datatype: var otherDoc:XML = XML(items[0]); However, even without that cast, the code generates no errors at compile time.

3.9 Up Next: Creating ClassesYour Own Datatypes!

  As we've seen in this chapter, datatypes and type checking are an essential part of programming in ActionScript 2.0. Now thatyou're familiar with how datatypes work and how they help you write better code, it's time to move on.

Chapter 4 you'll learn

Chapter 4. Classes This chapter covers the syntax and theory behind classes in ActionScript 2.0 and assumes a prior basic understanding of the

  how to define your own datatypes by creating classes. Learning to create a class is the first hands-on step down the path of theobject-oriented programmer.

Chapter 2 . Classes are the foundational

  structure of all object-oriented programs, making them arguably the most important aspect of OOP. This chapter is correspondingly lengthy and detailed but, even so, newer programmers can use it tolearn the basics of creating and using classes.

Chapter 5 , which shows, step-by-

  step, how to create a real-world class in the Flash authoring environment. We'll address the big-picture questions in Chapter 5 .

4.1 Defining Classes

  We'll learn more about the file structure of an object-orientedFlash application in Chapter 5 and Chapter 11 . For example, we might say " radius is nota member of Box," meaning that the Box class does not define any methods or properties named radius . The dynamic attribute

  But if we add the dynamic attribute to the class definition: dynamic class Box { } then the preceding size property addition is allowed and does not cause an error at compile time. The size and classPurpose properties are examples of dynamic properties, which can be added at runtime only to classes declared with the dynamic attribute (and to instances of such classes). The intrinsic attribute

  The intrinsic attribute is used only when distributing a compiled class without also distributing the class's source code, such asin the case of the built-in Flash Player classes. A class defined with the intrinsic attribute includes no method bodies orproperty values; it simply specifies property and method names and datatypes for the sake of compile-time type checking.

4.2 Constructor Functions (Take 1)

  For example, when we create an instance of our Boxclass, we might want to: Initialize the new instance's size (i.e., set its width and height properties) Represent the new instance on screen (i.e., call the draw( ) method)To initialize and perform setup tasks for new objects of a class, we create a constructor function. In the following code, lines 2 and 3 are the Box class's constructor function (or, more succinctly, "the Boxconstructor"): class Box { public function Box ( ) {} } Now that our Box class has an empty constructor function, we'll give the class some properties and methods.

4.3 Properties

As we learned in

Chapter 2 , classes use properties to store

  For example, every movie clip has its circle_mc and square_mc , we can set the instance property _rotation to 45 on circle_mc and to 120 on square_mc , causing each instance to be rotated individually on screen. The general syntax is: var propertyName:datatype = value; where propertyName is the property's identifier (case sensitive in ActionScript 2.0), datatype is the built-in or custom datatypeof the property, and value is the optional default value for the property ( value must be a compile-time constant expression,as discussed later).

Chapter 3 , is the type

  It indicates that ourwidth and height properties must store numeric data (i.e., data of the Number datatype). If, for example, we were to rename the description property to desc , we'd also have to change all code outside the class that referred to description .

4.3.1 Property Attributes

  For example, to add the public attribute to the height property of our Box class, we'd use: class Box { public var height:Number;} When a property has more than one attribute, the attributes can appear in any order. However, the public or private attributeis conventionally placed before the static attribute, as in: public static var someProperty :someDataType = someValue Furthermore, the public and private attributes cannot both be used to modify the same property definition; they are mutuallyexclusive. Restricting property access with the private and public attributes

  The private and public attributes are known as access control modifiers because they determine whether a property is accessible outside of the class that defines it. To make a property inaccessible to code outside of a class, we use the private attribute.

Dokumen baru

Aktifitas terkini

Download (1141 Halaman)


Oreilly Essential Actionscript 2 0 Jun 2004 Isbn Oreilly Eclipse May 2004 Isbn Oreilly Essential Silverlight 2 Up To Date Apr 2008 Isbn Oreilly Essential System Administration 3Rd Edition Aug 2002 Isbn Oreilly Bsd Hacks May 2004 Isbn Oreilly Office 2003 Xml May 2004 Isbn Oreilly Ajax Design Patterns Jun 2006 Isbn Oreilly Perl 6 Essentials Jun 2003 Isbn
Show more