Download user guide, user manual, owner manual and instructions guide
5 600 brands
1 870 000 user's guides
Search a brand
Advanced Search



Our partners wish to propose you the following products


Visit MACROMEDIA official site

User manual MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT REFERENCE GUIDE

Diplodocs help download the user guide MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT REFERENCE GUIDE.



Download the user manual MACROMEDIA FLASH MX 2004  
Download the complete
user guide (6183 Ko)
Need help, support, reviews, tips or troubleshooting for your MACROMEDIA FLASH MX 2004 products ?


You may also download the following manuals related to this product:
MACROMEDIA FLASH MX 2004 - FLASH JAVASCRIPT DICTIONARY
MACROMEDIA FLASH MX 2004 - USING FLASH
MACROMEDIA FLASH MX 2004 - USING COMPONENTS
MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT LANGUAGE REFERENCE
MACROMEDIA FLASH MX 2004 - LEARNING FLASH
MACROMEDIA FLASH MX 2004 - DATA TUTORIALS
MACROMEDIA FLASH MX 2004 FLASH LITE AUTHORING GUIDELINES FOR THE I-MODE SERVICE
MACROMEDIA FLASH MX 2004 - GETTING STARTED WITH FLASH
MACROMEDIA FLASH MX 2004 - USING ACTIONSCRIPT IN FLASH
Preview of the first 3 pages of manual

You either have JavaScript turned off or an old version of Adobe Flash Player
Get the latest Flash Player.
User guide MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT REFERENCE GUIDE

Detailed instructions for use are in the User's Guide.

ActionScript Reference Guide Trademarks Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Fontographer, FreeHand, Generator, HomeSite, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Flash, Macromedia M Logo and Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally. Third-Party Information This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites. Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com). SorensonTM SparkTM video compression and decompression technology licensed from Sorenson Media, Inc. Opera ® browser Copyright © 1995-2002 Opera Software ASA and its suppliers. All rights reserved. Apple Disclaimer APPLE COMPUTER, INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE ENCLOSED COMPUTER SOFTWARE PACKAGE, ITS MERCHANTABILITY OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES. THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY PROVIDES YOU WITH SPECIFIC LEGAL RIGHTS. THERE MAY BE OTHER RIGHTS THAT YOU MAY HAVE WHICH VARY FROM STATE TO STATE. Copyright © 2003 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without prior written approval of Macromedia, Inc. Part Number ZFL70M400 Acknowledgments Director: Erick Vera Project Management: Stephanie Gowin, Barbara Nelson Writing: Jody Bleyle, Mary Burger, Kim Diezel, Stephanie Gowin, Dan Harris, Barbara Herbert, Barbara Nelson, Shirley Ong, Tim Statler Managing Editor: Rosana Francescato Editing: Linda Adler, Mary Ferguson, Mary Kraemer, Noreen Maher, Antonio Padial, Lisa Stanziano, Anne Szabla Production Management: Patrice O'Neill Media Design and Production: Adam Barnett, Christopher Basmajian, Aaron Begley, John Francis, Jeff Harmon First Edition: Septermber 2003 Macromedia, Inc. 600 Townsend St. San Francisco, CA 94103 CONTENTS INTRODUCTION: Getting Started with ActionScript ....................... 9 Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 System requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Using the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Terms used in this document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 PART I: Welcome to ActionScript CHAPTER 1: What's New in Flash MX 2004 ActionScript. . . . . . . . . . . . . . . . . . 13 13 14 15 21 22 22 New and changed language elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . New security model and legacy SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Porting existing scripts to Flash Player 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ActionScript editor changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . New object-oriented programming model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CHAPTER 2: ActionScript Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 25 26 26 29 34 37 40 45 50 51 51 Differences between ActionScript and JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . Unicode support for ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Assigning data types to elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using operators to manipulate values in expressions . . . . . . . . . . . . . . . . . . . . . . . Specifying an object's path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 CHAPTER 3: Writing and Debugging Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Controlling when ActionScript runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Using the Actions panel and Script window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Using the ActionScript editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Debugging your scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Using the Output panel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Updating Flash Player for testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 PART II: Handling Events and Creating Interaction CHAPTER 4: Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Using event handler methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Using event listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Using button and movie clip event handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Creating movie clips with button states . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Event handler scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Scope of the "this" keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 CHAPTER 5: Creating Interaction with ActionScript . . . . . . . . . . . . . . . . . . . . . . 91 About events and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Controlling SWF file playback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Creating interactivity and visual effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Deconstructing a sample script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 PART III: Working with Objects and Classes CHAPTER 6: Using the Built-In Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 About classes and instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Overview of built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 CHAPTER 7: Working with Movie Clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 About controlling movie clips with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . 121 Calling multiple methods on a single movie clip . . . . . . . . . . . . . . . . . . . . . . . . . 122 Loading and unloading additional SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Specifying a root Timeline for loaded SWF files . . . . . . . . . . . . . . . . . . . . . . . . . 123 Loading JPEG files into movie clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 Changing movie clip position and appearance . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Dragging movie clips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Creating movie clips at runtime. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Adding parameters to dynamically created movie clips . . . . . . . . . . . . . . . . . . . . 128 Managing movie clip depths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Drawing shapes with ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Using movie clips as masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 4 Contents Handling movie clip events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Assigning a class to a movie clip symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Initializing class properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 CHAPTER 8: Working with Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 135 137 137 139 147 153 Using the TextField class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating text fields at runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the TextFormat class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Formatting text with Cascading Style Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using HTML-formatted text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating scrolling text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CHAPTER 9: Creating Classes with ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . 155 156 157 161 165 167 169 171 171 172 173 174 Principles of object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using classes: a simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating and using classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Instance and class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating and using interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Understanding the classpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Importing classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Implicit get/set methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating dynamic classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How classes are compiled and exported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PART IV: Working with External Data and Media CHAPTER 10: Working with External Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Sending and loading variables to and from a remote source . . . . . . . . . . . . . . . . . 177 Sending messages to and from Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Flash Player security features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 CHAPTER 11: Working with External Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 193 194 195 196 197 198 Overview of loading external media. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loading external SWF and JPEG files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loading external MP3 files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Reading ID3 tags in MP3 files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Playing back external FLV files dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preloading external media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Contents 5 PART V: Reference CHAPTER 12: ActionScript Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Sample entry for most ActionScript elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Sample entry for classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Contents of the dictionary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Accessibility class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Arguments class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Array class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Boolean class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 Button class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Camera class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 Color class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 ContextMenu class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 ContextMenuItem class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 CustomActions class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Date class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Error class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 Function class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 Key class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 LoadVars class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 LocalConnection class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 Math class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 Microphone class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 Mouse class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 MovieClip class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 MovieClipLoader class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544 NetConnection class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 NetStream class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556 Number class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569 Object class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 PrintJob class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 Selection class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 SharedObject class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617 Sound class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624 Stage class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640 String class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649 System class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 System.capabilities object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 System.security object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675 TextField class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 TextField.StyleSheet class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 TextFormat class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715 TextSnapshot object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 Video class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744 XML class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751 XMLNode class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773 XMLSocket class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774 6 Contents APPENDIX A: Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783 . . . . . . . . . . . . . . . . . . . 787 APPENDIX B: Operator Precedence and Associativity APPENDIX C: Keyboard Keys and Key Code Values . . . . . . . . . . . . . . . . . . . . . 789 789 790 791 792 Letters A to Z and standard numbers 0 to 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . Keys on the numeric keypad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Function keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Other keys. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . APPENDIX D: Writing Scripts for Earlier Versions of Flash Player. . . . . . . . . . . 795 About targeting older versions of Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . . 795 Using Flash MX 2004 to create content for Flash Player 4. . . . . . . . . . . . . . . . . . 796 APPENDIX E: Object-Oriented Programming with ActionScript 1 . . . . . . . . . . . 799 About ActionScript 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799 INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807 Contents 7 8 Contents INTRODUCTION Getting Started with ActionScript Macromedia Flash MX 2004 and Flash MX Professional 2004 are the professional standard authoring tools for producing high-impact web experiences. ActionScript is the language you use when you want to develop an application within Flash. You don't have to use ActionScript to use Flash, but if you want to provide user interactivity, work with objects other than those built into Flash (such as buttons and movie clips), or otherwise turn a SWF file into a more robust user experience, you'll probably want to use ActionScript. Intended audience This book assumes that you already have Flash MX 2004 or Flash MX Professional 2004 installed and know how to use it. You should know how to place objects on the Stage and manipulate them in the Flash authoring environment. If you have written programs before, ActionScript will feel familiar. But even if you haven't, ActionScript isn't hard to learn. It's easy to start with very simple commands and build more complexity as you go along. System requirements ActionScript does not have any system requirements in addition to Flash MX 2004 or Flash MX Professional 2004. However, the documentation assumes that you are using the default publishing settings for your Flash files: Flash Player 7 and ActionScript 2.0. If you change either of these settings, explanations and code samples shown in the documentation may not work correctly. Using the documentation This document provides an overview of ActionScript syntax, information on how to use ActionScript when working with different types of objects, and details on the syntax and usage of every language element. Start by learning the terminology and basic concepts used in the rest of the document (see Chapter 2, "ActionScript Basics," on page 25). Next, learn the mechanics of writing and debugging Flash scripts (see Chapter 3, "Writing and Debugging Scripts," on page 55). Before writing your own scripts, you should complete the lessons "Write Scripts with ActionScript" and "Create a Form with Conditional Logic and Send Data," which provide a hands-on introduction to working with ActionScript. To find these lessons, select Help > How Do I > Quick Tasks. 9 After you understand the basics, you are ready to use the information in the rest of this document as it applies to the specific effect you are trying to achieve. For example, if you want to learn how to write a script that performs a certain action when a user clicks the mouse, see Chapter 4, "Handling Events," on page 83. When you find information about a certain command you want to use, you can look up its entry in Chapter 12, "ActionScript Dictionary," on page 205; every language element is listed there in alphabetical order. Typographical conventions The following typographical conventions are used in this book: · · Code font indicates ActionScript code. Code font italic indicates an element, such as an ActionScript parameter or object name, that you replace with your own text when writing a script. Terms used in this document The following terms are used in this book: · · · · You refers to the developer who is writing a script or application. The user refers to the person who will be running your scripts and applications. Compile time is the time at which you publish, export, test, or debug your document. Runtime is the time at which your script is running in Flash Player. ActionScript terms such as method and object are defined in Chapter 2, "ActionScript Basics," on page 25. Additional resources Specific documentation about Flash and related products is available separately. · For information about working in the Flash authoring environment, see Using Flash Help. For information about working with components, see Using Components Help. · For information about creating communication applications with Flash Communication Server, see Developing Communications Applications and Managing Flash Communication Server. · For information about accessing web services with Flash applications, see Using Flash Remoting. The Macromedia DevNet website (www.macromedia.com/devnet) is updated regularly with the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, and other updates. Check the website often for the latest news on Flash and how to get the most out of the program. The Macromedia Flash Support Center (www.macromedia.com/support/flash) provides TechNotes, documentation updates, and links to additional resources in the Flash community. 10 Introduction: Getting Started with ActionScript PART I Welcome to ActionScript PART I This part includes basic information on the ActionScript language. Chapter 1 includes information on what is new or changed in ActionScript and Flash Player 7. If you have used ActionScript before, be sure to review this information carefully. If you are new to ActionScript, read Chapters 2 and 3 to get a good foundation for understanding ActionScript terminology and syntax and for learning how to write and debug your scripts. Chapter 1: What's New in Flash MX 2004 ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Chapter 2: ActionScript Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Chapter 3: Writing and Debugging Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 CHAPTER 1 What's New in Flash MX 2004 ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide several enhancements that make it easier for you to write more robust scripts using the ActionScript language. These new features, which are discussed in this chapter, include new language elements, improved editing and debugging tools (see "ActionScript editor changes" on page 21 and "Debugging changes" on page 22), and the introduction of a more object-oriented programming model (see "New object-oriented programming model" on page 22). This chapter also contains an extensive section that you should read carefully if you plan to publish any of your existing Flash MX or earlier files to Flash Player 7 (see "Porting existing scripts to Flash Player 7" on page 15). New and changed language elements This section describes the ActionScript language elements that are new or changed in Flash MX 2004. To use any of these elements in your scripts, you must target Flash Player 7 (the default) when you publish your documents. · The Array.sort() and Array.sortOn() methods let you add parameters to specify · · · · · · additional sorting options, such as ascending and descending sorting, whether to consider case sensitivity when sorting, and so on. The Button.menu, MovieClip.menu, and TextField.menu properties work with the new ContextMenu and ContextMenuItem classes to let you associate context menu items with Button, MovieClip, or TextField objects. The ContextMenu class and ContextMenuItem class let you customize the context menu that is displayed when a user right-clicks (Microsoft Windows) or Control-clicks (Macintosh) in Flash Player. The Error class and the throw and try..catch..finally commands let you implement more robust exception handling. The LoadVars.addRequestHeader() and XML.addRequestHeader() methods add or change HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. The MMExecute() function lets you issue Flash JavaScript API commands from ActionScript. (Windows only) The Mouse.onMouseWheel event listener is generated when the user scrolls using the mouse wheel. 13 · The MovieClip.getNextHighestDepth() method lets you create MovieClip instances at runtime and be guaranteed that their objects render in front of the other objects in a parent movie clip's z-order space. The MovieClip.getInstanceAtDepth() method lets you access dynamically created MovieClip instances using the depth as a search index. The MovieClip.getSWFVersion() method lets you determine which version of Flash Player is supported by a loaded SWF file. The MovieClip.getTextSnapshot() method and the TextSnapshot object let you work with text that is in static text fields in a movie clip. The MovieClip._lockroot property lets you specify that a movie clip will act as _root for any movie clips loaded into it, or that the meaning of _root in a movie clip won't change if that movie clip is loaded into another movie clip. The MovieClipLoader class lets you monitor the progress of files as they are being loaded into movie clips. The NetConnection class and NetStream class let you stream local video files (FLV files). The PrintJob class gives you (and the user) more control over printing from Flash Player. The Sound.onID3 event handler provides access to ID3 data associated with a Sound object that contains an MP3 file. The Sound.ID3 property provides access to the metadata that is part of an MP3 file. The System class has new objects and methods, and the System.capabilities object has several new properties. The TextField.condenseWhite property lets you remove extra white space from HTML text fields that are rendered in a browser. The TextField.mouseWheelEnabled property lets you specify whether a text field's contents should scroll when the mouse pointer is positioned over a text field and the user rolls the mouse wheel. The TextField.StyleSheet class lets you create a style sheet object that contains text formatting rules such as font size, color, and other formatting styles. The TextField.styleSheet property lets you attach a style sheet object to a text field. The TextFormat.getTextExtent() method accepts a new parameter, and the object it returns contains a new member. The XML.addRequestHeader() method lets you add or change HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. · · · · · · · · · · · · · · · New security model and legacy SWF files Rules for how Flash Player determines whether two domains are the same have changed in Flash Player 7. In addition, rules that determine whether and how a SWF file served from an HTTP domain can access a SWF file or load data from an HTTPS domain have changed. In most cases, these changes won't affect you unless you are porting your existing SWF files to Flash Player 7. However, if you have SWF files published for Flash Player 6 or earlier that load data from a file stored on a server, and the calling SWF is playing in Flash Player 7, the user might see a dialog box that didn't appear before, asking whether to allow access. You can prevent this dialog box from appearing by implementing a policy file on the site where the data is stored. For more information on this dialog box, see "About compatibility with previous Flash Player security models" on page 191. 14 Chapter 1: What's New in Flash MX 2004 ActionScript You might also need to implement a policy file if you are using runtime shared libraries. If either the loading or loaded SWF file is published for Flash Player 7 and the loading and loaded files aren't served from the exact same domain, use a policy file to permit access. For more information on policy files, see "About allowing cross-domain data loading" on page 190. Porting existing scripts to Flash Player 7 As with any new release, Flash Player 7 supports more ActionScript commands than previous versions of the player; you can use these commands to implement more robust scripts. (See "New and changed language elements" on page 13.)However, if you used any of these commands in your existing scripts, the script might not work correctly if you publish it for Flash Player 7. For example, if you have a script with a function named Error, the script might appear to compile correctly but might not run as expected in Flash Player 7, because Error is now a built-in class (and thus a reserved word) in ActionScript. You can fix your script by renaming the Error function to something else, such as ErrorCondition. Also, Flash Player 7 implements a number of changes that affect how one SWF file can access another SWF file, how external data can be loaded, and how local settings and data (such as privacy settings and locally persistent shared objects) can be accessed. Finally, the behavior of some existing features has changed. If you have existing scripts written for Flash Player 6 or earlier that you want to publish for Flash Player 7, you might need to modify the scripts so they conform with the implementation of Flash Player 7 and work as designed. These modifications are discussed in this section. ECMA-262 Edition 4 compliance Several changes have been implemented in Flash Player 7 to conform more closely to the ECMA-262 Edition 4 proposal (see www.mozilla.org/js/language/es4/index.html). In addition to the class-based programming techniques available in ActionScript 2.0 (see "New object-oriented programming model" on page 22), other features have been added and certain behaviors have changed. Also, when publishing for Flash Player 7 and using ActionScript 2.0, you can cast one object type to another. For more information, see "Casting objects" on page 39. These capabilities don't require you to update existing scripts; however, you may want to use them if you publish your scripts to Flash Player 7 and then continue to revise and enhance them. Porting existing scripts to Flash Player 7 15 Unlike the changes mentioned above, the changes listed in the following table (some of which also improve ECMA compliance) may cause existing scripts to work differently than they did previously. If you used these features in existing scripts that you want to publish to Flash Player 7, review the changes to make sure your code still works as intended or to determine whether you need to rewrite your code. In particular, because undefined is evaluated differently in certain cases, you should initialize all variables in scripts that you port to Flash Player 7. SWF file published for Flash Player 7 Case sensitivity is supported (variable names that differ only in capitalization are interpreted as being different variables). This change also affects files loaded with #include and external variables loaded with LoadVars.load(). For more information, see "Case sensitivity" on page 29. Evaluating undefined in a numeric context returns NaN. myCount +=1; trace(myCount); // NaN SWF file published for earlier versions of Flash Player Case sensitivity is not supported (variable names that differ only in capitalization are interpreted as being the same variable). Evaluating undefined in a numeric context returns 0. myCount +=1; trace(myCount); // 1 When undefined is converted to a string, the result is When undefined is converted to a string, the result is "" (an empty string). undefined. firstname = "Joan "; lastname = "Flender"; trace(firstname + middlename + lastname); // Joan undefinedFlender firstname = "Joan "; lastname = "Flender"; trace(firstname + middlename + lastname); // Joan Flender When you convert a string to a Boolean value, the result is true if the string has a length greater than zero; the result is false for an empty string. When setting the length of an array, only a valid number string sets the length. For example, "6" works but " 6" or "6xyz" does not. my_array=new Array(); my_array[" 6"] ="x"; trace(my_array.length); // 0 my_array["6xyz"] ="x"; trace(my_array.length); // 0 my_array["6"] ="x"; trace(my_array.length); // 7 When you convert a string to a Boolean value, the string is first converted to a number; the result is true if the number is nonzero, false otherwise. When setting the length of an array, even a malformed number string sets the length: my_array=new Array(); my_array[" 6"] ="x"; trace(my_array.length); // 7 my_array["6xyz"] ="x"; trace(my_array.length); // 7 my_array["6"] ="x"; trace(my_array.length); // 7 16 Chapter 1: What's New in Flash MX 2004 ActionScript Domain-name rules for settings and local data In Flash Player 6, superdomain matching rules are used by default when accessing local settings (such as camera or microphone access permissions) or locally persistent data (shared objects). That is, the settings and data for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com are shared, and are all stored at xyz.com. In Flash Player 7, exact-domain matching rules are used by default. That is, the settings and data for a file hosted at here.xyz.com are stored at here.xyz.com, the settings and data for a file hosted at there.xyz.com are stored at there.xyz.com, and so on. A new property, System.exactSettings, lets you specify which rules to use. This property is supported for files published for Flash Player 6 or later. For files published for Flash Player 6, the default value is false, which means superdomain matching rules are used. For files published for Flash Player 7, the default value is true, which means exact-domain matching rules are used. If you use settings or persistent local data and want to publish a Flash Player 6 SWF file for Flash Player 7, you might need to set this value to false in the ported file. For more information, see System.exactSettings on page 662. Cross-domain and subdomain access between SWF files When you develop a series of SWF files that communicate with each other--for example, when using loadMovie(), MovieClip.loadMovie(), MovieClipLoader.LoadClip(), or Local Connection objects--you might host the movies in different domains, or in different subdomains of a single superdomain. In files published for Flash Player 5 or earlier, there were no restrictions on cross-domain or subdomain access. In files published for Flash Player 6, you could use the LocalConnection.allowDomain handler or System.security.allowDomain() method to specify permitted cross-domain access (for example, to let a file at someSite.com be accessed by a file at someOtherSite.com), and no command was needed to permit subdomain access (for example, a file at www.someSite.com could be accessed by a file at store.someSite.com). Files published for Flash Player 7 implement access between SWF files differently from earlier versions in two ways. First, Flash Player 7 implements exact-domain matching rules instead of superdomain matching rules. Therefore, the file being accessed (even if it is published for a Player version earlier than Flash Player 7) must explicitly permit cross-domain or subdomain access; this topic is discussed below. Second, a file hosted at a site using a secure protocol (HTTPS) must explicitly permit access from a file hosted at a site using an insecure protocol (HTTP or FTP); this topic is discussed in the next section (see "HTTP to HTTPS protocol access between SWF files" on page 19). Porting existing scripts to Flash Player 7 17 Because Flash Player 7 implements exact-domain matching rules instead of superdomain matching rules, you might have to modify existing scripts if you want to access them from files that are published for Flash Player 7. (You can still publish the modified files for Flash Player 6.) If you used any LocalConnection.allowDomain() or System.security.allowDomain() statements in your files and specified superdomain sites to permit, you must change your parameters to specify exact domains instead. The following code shows an example of the kinds of changes you might have to make: // Flash Player 6 commands in a SWF file at www.anyOldSite.com // to allow access by SWF files that are hosted at www.someSite.com // or at store.someSite.com System.security.allowDomain("someSite.com"); my_lc.allowDomain = function(sendingDomain) { return(sendingDomain=="someSite.com"); } // Corresponding commands to allow access by SWF files // that are published for Flash Player 7 System.security.allowDomain("www.someSite.com", "store.someSite.com"); my_lc.allowDomain = function(sendingDomain) { return(sendingDomain=="www.someSite.com" || sendingDomain=="store.someSite.com"); } You might also have to add statements like these to your files if you aren't currently using them. For example, if your SWF file is hosted at www.someSite.com and you want to allow access by a SWF file published for Flash Player 7 at store.someSite.com, you must add statements like the following to the file at www.someSite.com (you can still publish the file at www.someSite.com for Flash Player 6): System.security.allowDomain("store.someSite.com"); my_lc.allowDomain = function(sendingDomain) { return(sendingDomain=="store.someSite.com"); } To summarize, you might have to modify your files to add or change allowDomain statements if you publish files for Flash Player 7 that meet the following conditions: · You implemented cross-SWF scripting (using loadMovie(), MovieClip.loadMovie(), · · or Local Connection objects). The called SWF file (of any version) is not hosted at a site using a secure protocol (HTTPS), or the calling and called SWF files are both hosted at HTTPS sites. (If only the called SWF file is HTTPS, see "HTTP to HTTPS protocol access between SWF files" on page 19.) The SWF files are not in same domain (for example, one file is at www.domain.com and one is at store.domain.com). MovieClipLoader.LoadClip(), 18 Chapter 1: What's New in Flash MX 2004 ActionScript You have to make the following changes: · If the called SWF file is published for Flash Player 7, include System.security.allowDomain · or LocalConnection.allowDomain in the called SWF file, using exact domainname matching. If the called SWF file is published for Flash Player 6, modify the called file to add or change a System.security.allowDomain or LocalConnection.allowDomain statement, using exact domain-name matching, as shown in the code examples earlier in this section. You can publish the modified file for either Flash Player 6 or 7. If the called SWF file is published for Flash Player 5 or earlier, port the called file to Flash Player 6 or 7 and add a System.security.allowDomain statement, using exact domain-name matching, as shown in the code examples earlier in this section. (LocalConnection objects aren't supported in Flash Player 5 or earlier.) · HTTP to HTTPS protocol access between SWF files As discussed in the previous section, rules for cross-domain and subdomain access have changed in Flash Player 7. In addition to the exact-domain matching rules now being implemented, you must explicitly permit files hosted at sites using a secure protocol (HTTPS) to be accessed by files hosted at sites using an insecure protocol. Depending on whether the called file is published for Flash Player 7 or Flash Player 6, you must implement either one of the allowDomain statements (see "Cross-domain and subdomain access between SWF files" on page 17), or use the new LocalConnection.allowInsecure Domain or System.security.allowInsecureDomain() statements. Warning: Implementing an allowInsecureDomain() statement compromises the security offered by the HTTPS protocol. You should make these changes only if you can't reorganize your site so that all SWF files are served from the HTTPS protocol. The following code shows an example of the kinds of changes you might have to make: // Commands in a Flash Player 6 SWF file at https://www.someSite.com // to allow access by Flash Player 7 SWF files that are hosted // at http://www.someSite.com or at http://www.someOtherSite.com System.security.allowDomain("someOtherSite.com"); my_lc.allowDomain = function(sendingDomain) { return(sendingDomain=="someOtherSite.com"); } // Corresponding commands in a Flash Player 7 SWF file // to allow access by Flash Player 7 SWF files that are hosted // at http://www.someSite.com or at http://www.someOtherSite.com System.security.allowInsecureDomain("www.someSite.com", "www.someOtherSite.com"); my_lc.allowInsecureDomain = function(sendingDomain) { return(sendingDomain=="www.someSite.com" || sendingDomain=="www.someOtherSite.com"); } You might also have to add statements like these to your files if you aren't currently using them. A modification might be necessary even if both files are in same domain (for example, a file in http://www.domain.com is calling a file in https://www.domain.com). Porting existing scripts to Flash Player 7 19 To summarize, you might have to modify your files to add or change statements if you publish files for Flash Player 7 that meet the following conditions: · You implemented cross-SWF scripting (using loadMovie(), MovieClip.loadMovie(), MovieClipLoader.LoadClip(), or Local Connection objects). · The calling file is not hosted using an HTTPS protocol, and the called file is HTTPS. You must make the following changes: · If the called file is published for Flash Player 7, include System.security.allowInsecureDomain or LocalConnection.allowInsecureDomain in the called file, using exact domain-name matching, as shown in the code examples earlier in this section. This statement is required even if the calling and called SWF files are in same domain. If the called file is published for Flash Player 6 or earlier, and both the calling and called files are in same domain (for example, a file in http://www.domain.com is calling a file in https:// www.domain.com), no modification is needed. If the called file is published for Flash Player 6, the files are not in same domain, and you don't want to port the called file to Flash Player 7, modify the called file to add or change a System.security.allowDomain or LocalConnection.allowDomain statement, using exact domain-name matching, as shown in the code examples earlier in this section. If the called file is published for Flash Player 6 and you want to port the called file to Flash Player 7, include System.security.allowInsecureDomain or LocalConnection.allowInsecureDomain in the called file, using exact domain-name matching, as shown in the code examples earlier in this section. This statement is required even if both files are in same domain. If the called file is published for Flash Player 5 or earlier, and both files are not in the same domain, you can do one of two things. You can either port the called file to Flash Player 6 and add or change a System.security.allowDomain statement, using exact domain-name matching, as shown in the code examples earlier in this section, or you can port the called file to Flash Player 7, and include a System.security.allowInsecureDomain statement in the called file, using exact domain-name matching, as shown in the code examples earlier in this section. · · · · Server-side policy files for permitting access to data A Flash document can load data from an external source by using one of the following data loading calls: XML.load(), XML.sendAndLoad(), LoadVars.load(), Flash Remoting (NetServices.createGatewayConnection). Also, a SWF file can import runtime shared libraries (RSLs), or assets defined in another SWF file, at runtime. By default, the data or RSL must reside in the same domain as the SWF file that is loading that external data or media. To make data and assets in runtime shared libraries available to SWF files in different domains, you should use a cross-domain policy file. A cross-domain policy file is an XML file that provides a way for the server to indicate that its data and documents are available to SWF files served from certain domains, or from all domains. Any SWF file that is served from a domain specified by the server's policy file is permitted to access data or RSLs from that server. LoadVars.sendAndLoad(), loadVariables(), loadVariablesNum(), MovieClip.loadVariables(), XMLSocket.connect(), and Macromedia 20 Chapter 1: What's New in Flash MX 2004 ActionScript If you are loading external data, you should create policy files even if you don't plan to port any of your files to Flash Player 7. If you are using RSLs, you should create policy files if either the calling or called file is published for Flash Player 7. For more information, see "About allowing cross-domain data loading" on page 190. ActionScript editor changes The ActionScript editor has been updated in a number of ways to make it more robust and easier to use. These changes are summarized in this section. Word wrapping You can now use the Options pop-up menu in the Script pane, Debugger panel, and Output panel to enable or disable word wrapping. You can also toggle word wrapping using the pop-up menu in the Actions panel. The keyboard shortcut is Control+Shift+W (Windows) or Command+Shift+W (Macintosh). Viewing context-sensitive help When your pointer is positioned over an ActionScript language element in the Actions toolbox or in the Script pane, you can use the View Help item in the context menu to display a help page about that element. Importing scripts When you select Import Script from the pop-up menu in the Actions panel, the imported script is copied into the script at the insertion point in your code file. In previous versions of Flash, importing a script overwrote the contents of the existing script. Single-click breakpoints To add a debugging breakpoint before a line of code in the Debugger panel or the Script pane of the Actions panel, you can click in the left margin. In previous versions of Flash, clicking in the left margin selected a line of code. The new way to select a line of code is to Control-click (Windows) or Command-click (Macintosh). Normal and expert modes no longer in Actions panel In previous versions of Flash, you could work in the Actions panel either in normal mode, in which you filled in options and parameters to create code, or in expert mode, in which you added commands directly into the Script pane. In Flash MX 2004 and Flash MX Professional 2004, you can work in the Actions panel only by adding commands directly to the Script pane. You can still drag commands from the Actions toolbox into the Script pane or use the Add (+) button above the Script pane to add commands to a script. Pinning multiple scripts You can pin multiple scripts within a FLA file along the bottom of the Script pane in the Actions panel. In previous versions of Flash, you could pin only one script at a time. Script navigator The left side of the Actions panel now contains two panes: the Actions toolbox and a new Script navigator. The Script navigator is a visual representation of the structure of your FLA file; you can navigate through your FLA file here to locate ActionScript code. Integrated Script window for editing external files (Flash Professional only) You can use the ActionScript editor in a Script window (separate from the Actions panel) to write and edit external script files. Syntax coloring, code hinting, and other preferences are supported in the Script window, and the Actions toolbox is also available. To display the Script window, use File > New and then select the type of external file you want to edit. You can have multiple external files open at the same time; filenames are displayed on tabs across the top of the Script window. (The tabs appear only in Windows.) ActionScript editor changes 21 Debugging changes This section describes changes that improve your ability to debug your scripts. Output window changed to Output panel You can now move and dock the Output panel in the same way as any other panel in Flash. Improved error reporting at compile time In addition to providing more robust exception handling, ActionScript 2.0 provides a number of new compile-time errors. For more information, see Appendix A, "Error Messages," on page 783. Improved exception handling The Error class and the throw and try..catch..finally commands let you implement more robust exception handling. New object-oriented programming model The ActionScript language has grown and developed since its introduction several years ago. With each new release of Flash, additional keywords, objects, methods, and other language elements have been added to the language. However, unlike earlier releases of Flash, Flash MX 2004 and Flash MX Professional 2004 introduce several new language elements that implement objectoriented programming in a more standard way than before. Because these language elements represent a significant enhancement to the core ActionScript language, they represent a new version of ActionScript itself: ActionScript 2.0. ActionScript 2.0 is not a new language. Rather, it comprises a core set of language elements that make it easier to develop object-oriented programs. With the introduction of keywords such as class, interface, extends, and implements, ActionScript syntax is now easier to learn for programmers familiar with other languages. New programmers can learn more standard terminology that they can apply to other object-oriented languages they may study in the future. ActionScript 2.0 supports all the standard elements of the ActionScript language; it simply enables you to write scripts that more closely adhere to standards used in other object-oriented languages, such as Java. ActionScript 2.0 should be of interest primarily to intermediate or advanced Flash developers who are building applications that require the implementation of classes and subclasses. ActionScript 2.0 also lets you declare the object type of a variable when you create it (see "Strict data typing" on page 38) and provides significantly improved compiler errors (see Appendix A, "Error Messages," on page 783). The language elements that are new in ActionScript 2.0 are listed below. · · · · · · · · · · · class extends implements interface dynamic static public private get set import 22 Chapter 1: What's New in Flash MX 2004 ActionScript Key facts about ActionScript 2.0 include the following points: · Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external script · files, with a single class defined in each script; that is, classes and interfaces cannot be defined in the Actions panel. You can import individual class files implicitly (by storing them in a location specified by global or document-specific search paths and then using them in a script) or explicitly (by using the import command); you can import packages (collections of class files in a directory) by using wildcards. Applications developed with ActionScript 2.0 are supported by Flash Player 6 and later. · Caution: The default publish setting for new files created in Flash MX 2004 is ActionScript 2.0. If you plan to modify an existing FLA file to use ActionScript 2.0 syntax, ensure that the FLA file specifies ActionScript 2.0 in its publish settings. If it does not, your file will compile incorrectly, although Flash will not generate compiler errors. For more information on using ActionScript 2.0 to write object-oriented programs in Flash, see Chapter 9, "Creating Classes with ActionScript 2.0," on page 155. New object-oriented programming model 23 24 Chapter 1: What's New in Flash MX 2004 ActionScript CHAPTER 2 ActionScript Basics ActionScript has rules of grammar and punctuation that determine which characters and words are used to create meaning and in which order they can be written. For example, in English, a period ends a sentence. In ActionScript, a semicolon ends a statement. The following general rules apply to all ActionScript. Most ActionScript terms also have individual requirements; for the rules for a specific term, see its entry in Chapter 12, "ActionScript Dictionary," on page 205. Differences between ActionScript and JavaScript ActionScript is similar to the core JavaScript programming language. You don't need to know JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will appear familiar. This manual does not attempt to teach general programming. There are many resources that provide more information about general programming concepts and the JavaScript language. · The European Computers Manufacturers Association (ECMA) document ECMA-262 is · derived from JavaScript and serves as the international standard for the JavaScript language. ActionScript is based on the ECMA-262 specification. Netscape DevEdge Online has a JavaScript Developer Central site (http:// developer.netscape.com/tech/javascript/index.html) that contains documentation and articles useful for understanding ActionScript. The most valuable resource is the Core JavaScript Guide. Some of the differences between ActionScript and JavaScript are as follows:. · ActionScript does not support browser-specific objects such as Document, Window, and Anchor. · ActionScript does not completely support all the JavaScript built-in objects. · ActionScript does not support some JavaScript syntax constructs, such as statement labels. · In ActionScript, the eval() action can perform only variable references. 25 Unicode support for ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 support Unicode text encoding for ActionScript. This means that you can include text in different languages in an ActionScript file. For example, you could include text in English, Japanese, and French in the same file. You can set ActionScript preferences to specify the type of encoding to use when importing or exporting ActionScript files. You can select either UTF-8 encoding or Default Encoding. UTF-8 is 8-bit Unicode format; Default Encoding is the encoding form supported by the language your system is currently using, also called the traditional code page. In general, if you are importing or exporting ActionScript files in UTF-8 format, use the UTF-8 preference. If you are importing or exporting files in the traditional code page in use on your system, use the Default Encoding preference. If text in your scripts doesn't look as expected when you open or import a file, change the import encoding preference. If you receive a warning message when exporting ActionScript files, you can change the export encoding preference or turn this warning off in ActionScript preferences. To select text encoding options for importing or exporting ActionScript files: 1 In the Preferences dialog box (Edit > Preferences), click the ActionScript tab. 2 Under Editing Options, do one or both of the following: For Open/Import, select UTF-8 to open or import using Unicode encoding, or select Default Encoding to open or import using the encoding form of the language currently used by your system. For Save/Export, select UTF-8 to save or export using Unicode encoding, or select Default Encoding to save or export using the encoding form of the language currently used by your system. To turn the export encoding warning off or on: 1 In the Preferences dialog box (Edit > Preferences), click the Warnings tab. 2 Select or deselect Warn on Encoding Conflicts When Exporting .as Files. Caution: The Test Movie command (see "Debugging your scripts" on page 68) will fail if any part of the SWF file path has characters that cannot be represented using the MBCS encoding scheme. For example, Japanese paths on an English system will not work. All areas of the application that use the external player are subject to this limitation. Terminology As with any scripting language, ActionScript uses its own terminology. The following list provides an introduction to important ActionScript terms. Actions are statements that instruct a SWF file to do something while it is playing. For example, gotoAndStop() sends the playhead to a specific frame or label. In this manual, the terms action and statement are interchangeable. Boolean is a true or false value. Classes are data types that you can create to define a new type of object. To define a class, you use the class keyword in an external script file (not in a script you are writing in the Actions panel). 26 Chapter 2: ActionScript Basics Constants are elements that don't change. For example, the constant Key.TAB always has the same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values. Constructors are functions that you use to define the properties and methods of a class. By definition, constructors are functions within a class definition that have the same name as the class. For example, the following code defines a Circle class and implements a constructor function: // file Circle.as class Circle { private var radius:Number private var circumference:Number // constructor function Circle(radius:Number) { circumference = 2 * Math.PI * radius; } } The term constructor is also used when you create (instantiate) an object based on a particular class. The following statements are constructors for the built-in Array class and the custom Circle class: my_array:Array = new Array(); my_circle:Circle = new Circle(); Data types describe the kind of information a variable or ActionScript element can hold. The ActionScript data types are String, Number, Boolean, Object, MovieClip, Function, null, and undefined. For more information, see "About data types" on page 34. Events are actions that occur while a SWF file is playing. For example, different events are generated when a movie clip loads, the playhead enters a frame, the user clicks a button or movie clip, or the user types on the keyboard. or load. There are two kinds of ActionScript event handlers: event handler methods and event listeners. (There are also two event handlers, on() and onClipEvent(), that you can assign directly to buttons and movie clips.) In the Actions toolbox, each ActionScript object that has event handler methods or event listeners has a subcategory called Events or Listeners. Some commands can be used both as event handlers and as event listeners and are included in both subcategories. Expressions are any legal combination of ActionScript symbols that represent a value. An expression consists of operators and operands. For example, in the expression x + 2, x and 2 are operands and + is an operator. Functions are blocks of reusable code that can be passed parameters and can return a value. For more information, see "Creating functions" on page 51. Identifiers are Event handlers are special actions that manage events such as mouseDown names used to indicate a variable, property, object, function, or method. The first character must be a letter, underscore (_), or dollar sign ($). Each subsequent character must be a letter, number, underscore, or dollar sign. For example, firstName is the name of a variable. Instances are objects that belong to a certain class. Each instance of a class contains all the properties and methods of that class. For example, all movie clips are instances of the MovieClip class, so you can use any of the methods or properties of the MovieClip class with any movie clip instance. Terminology 27 Instance names are unique names that let you target movie clip and button instances in scripts. You use the Property inspector to assign instance names to instances on the Stage. For example, a master symbol in the library could be called counter and the two instances of that symbol in the SWF file could have the instance names scorePlayer1_mc and scorePlayer2_mc. The following code sets a variable called score inside each movie clip instance by using instance names: _root.scorePlayer1_mc.score += 1; _root.scorePlayer2_mc.score -= 1; You can use special suffixes when naming instances so that code hints (see "Using code hints" on page 63) appear as you type your code. For more information, see "Using suffixes to trigger code hints" on page 62. Keywords are reserved words that have special meaning. For example, var is a keyword used to declare local variables. You cannot use a keyword as an identifier. For example, var is not a legal variable name. For a list of keywords, see "Keywords" on page 33. Methods are functions associated with a class. For example, getBytesLoaded() is a built-in method associated with the MovieClip class. You can also create functions that act as methods, either for objects based on built-in classes or for objects based on classes that you create. For example, in the following code, clear() becomes a method of a controller object that you have previously defined: function reset(){ this.x_pos = 0; this.x_pos = 0; } controller.clear = reset; controller.clear(); Objects are collections of properties and methods; each object has its own name and is an instance of a particular class. Built-in objects are predefined in the ActionScript language. For example, the built-in Date object provides information from the system clock. are terms that calculate a new value from one or more values. For example, the addition (+) operator adds two or more values together to produce a new value. The values that operators manipulate are called operands. Parameters (also called arguments) are placeholders that let you pass values to functions. For example, the following welcome() function uses two values it receives in the parameters firstName and hobby: function welcome(firstName, hobby) { welcomeText = "Hello, " + firstName + "I see you enjoy " + hobby; } Packages Operators are directories that contain one or more class files, and reside in a designated classpath directory (see "Understanding the classpath" on page 169). are attributes that define an object. For example, _visible is a property of all movie clips that defines whether a movie clip is visible or hidden. Properties 28 Chapter 2: ActionScript Basics are hierarchical addresses of movie clip instance names, variables, and objects in a SWF file. You name a movie clip instance in the movie clip Property inspector. (The main Timeline always has the name _root.) You can use a target path to direct an action at a movie clip or to get or set the value of a variable. For example, the following statement is the target path to the variable volume inside the movie clip stereoControl: _root.stereoControl.volume Target paths For more information on target paths, see "Absolute and relative target paths" in Using Flash Help. Variables are identifiers that hold values of any data type. Variables can be created, changed, and updated. The values they store can be retrieved for use in scripts. In the following example, the identifiers on the left side of the equal signs are variables: var x = 5; var name = "Lolo"; var c_color = new Color(mcinstanceName); For more information on variables, see "About variables" on page 40. Syntax As with any language, ActionScript has syntax rules that you must follow in order to create scripts that can compile and run correctly. This section describes the elements that comprise ActionScript syntax. Case sensitivity In a case-sensitive programming language, variable names that differ only in case (book and Book) are considered different from each other. Therefore, it's good practice to follow consistent capitalization conventions, such as those used in this manual, to make it easy to identify names of functions and variables in ActionScript code. When you publish files for Flash Player 7 or later, Flash implements case sensitivity whether you are using ActionScript 1 or ActionScript 2.0. This means that keywords, class names, variables, method names, and so on are all case sensitive. For example: // In file targeting Flash Player 7 // and either ActionScript 1 or ActionScript 2.0 // // Sets properties of two different objects cat.hilite = true; CAT.hilite = true; // Creates three different variables var myVar=10; var myvar=10; var mYvAr=10; // Does not generate an error var array = new Array(); var date = new Date(); This change also affects external variables loaded with LoadVars.load(). Syntax 29 In addition, case sensitivity is implemented for external scripts, such as ActionScript 2.0 class files or scripts that you import using the #include command. If you are publishing files for Flash Player 7 and have previously created external files that you add to your scripts by using the #include statement, you should review each file and confirm that you used consistent capitalization throughout. One way to do this is to open the file in the Script window (Flash Professional only) or, in a new FLA file, set your publish settings to Flash Player 7 and copy the file's contents into the Actions panel. Then use the Check Syntax button (see "Checking syntax and punctuation" on page 66) or publish your file; errors that are caused by naming conflicts appear in the Output panel. When Syntax coloring is enabled, language elements written with correct capitalization are blue by default. For more information, see "Keywords" on page 33 and "Syntax highlighting" on page 61. Dot syntax In ActionScript, a dot (.) is used to indicate the properties or methods related to an object or movie clip. It is also used to identify the target path to a movie clip, variable, function, or object. A dot syntax expression begins with the name of the object or movie clip followed by a dot, and ends with the element you want to specify. For example, the _x movie clip property indicates a movie clip's x axis position on the Stage. The expression ballMC._x refers to the _x property of the movie clip instance ballMC. As another example, submit is a variable set in the form movie clip, which is nested inside the movie clip shoppingCart. The expression shoppingCart.form.submit = true sets the submit variable of the instance form to true. play() method of the ball_mc movie clip instance ball_mc, as shown in the following statement: ball_mc.play(); Expressing a method of an object or movie clip follows the same pattern. For example, the moves the playhead in the Timeline of Dot syntax also uses two special aliases, _root and _parent. The alias _root refers to the main Timeline. You can use the _root alias to create an absolute target path. For example, the following statement calls the function buildGameBoard() in the movie clip functions on the main Timeline: _root.functions.buildGameBoard(); You can use the alias _parent to refer to a movie clip in which the current object is nested. You can also use _parent to create a relative target path. For example, if the movie clip dog_mc is nested inside the movie clip animal_mc, the following statement on the instance dog_mc tells animal_mc to stop: _parent.stop(); Slash syntax Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This syntax is still supported by Flash Player 7, but its use is not recommended, and slash syntax is not supported in ActionScript 2.0. However, if you are creating content intended specifically for Flash Player 4, you must use slash syntax. For more information, see "Using slash syntax" on page 797. 30 Chapter 2: ActionScript Basics Curly braces ActionScript event handlers, class definitions, and functions are grouped together into blocks with curly braces ({}). You can put the opening brace on the same line as your declaration or on the next line, as shown in the following examples. To make your code easier to read, it's a good idea to choose one format and use it consistently. // Event handler on(release) { myDate = new Date(); currentMonth = myDate.getMonth(); } on(release) { myDate = new Date(); currentMonth = myDate.getMonth(); } // Class class Circle(radius) { } class Square(side) { } // Function circleArea = function(radius) { return radius * radius * MATH.PI; } squareArea = function(side) { return side * side; } You can check for matching curly braces in your scripts; see "Checking syntax and punctuation" on page 66. Semicolons An ActionScript statement is terminated with a semicolon (;), as shown in these examples: var column = passedDate.getDay(); var row = 0; If you omit the terminating semicolon, Flash still compiles your script successfully. However, using semicolons is good scripting practice. Syntax 31 Parentheses When you define a function, place any parameters inside parentheses: function myFunction (name, age, reader){ // your code here } When you call a function, include any parameters passed to the function in parentheses, as shown here: myFunction ("Steve", 10, true); You can also use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read. (See "Operator precedence and associativity" on page 45.) You also use parentheses to evaluate an expression on the left side of a dot in dot syntax. For example, in the following statement, the parentheses cause new Color(this) to evaluate and create a Color object: onClipEvent(enterFrame) { (new Color(this)).setRGB(0xffffff); } If you don't use parentheses, you must add a statement to evaluate the expression: onClipEvent(enterFrame) { myColor = new Color(this); myColor.setRGB(0xffffff); } You can check for matching parentheses in your scripts; see "Checking syntax and punctuation" on page 66. Comments Using comments to add notes to scripts is highly recommended. Comments are useful for keeping track of what you intended and for passing information to other developers if you work in a collaborative environment or are providing samples. Even a simple script is easier to understand if you make notes as you create it. To indicate that a line or portion of a line is a comment, precede the comment with two forward slashes (//): on(release) { // create new Date object myDate = new Date(); currentMonth = myDate.getMonth(); // convert month number to month name monthName = calcMonth(currentMonth); year = myDate.getFullYear(); currentDate = myDate.getDate(); } When Syntax coloring is enabled (see "Syntax highlighting" on page 61), comments are gray by default. Comments can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords. If you want to "comment out" an entire portion of your script, place it in a comment block rather than adding // at the beginning of each line. This technique is easier and is useful when you want to test only parts of a script by commenting out large chunks of it. 32 Chapter 2: ActionScript Basics To create a comment block, place /* at the beginning of the commented lines and */ at the end. For example, when the following script runs, none of the code in the comment block is executed: // The code below runs var x:Number = 15; var y:Number = 20; // The code below doesn't run /* on(release) { // create new Date object myDate = new Date(); currentMonth = myDate.getMonth(); // convert month number to month name monthName = calcMonth(currentMonth); year = myDate.getFullYear(); currentDate = myDate.getDate(); } */ // The code below runs var name:String = "My name is"; var age:Number = 20; Keywords ActionScript reserves words for specific use within the language, so you can't use them as identifiers, such as variable, function, or label names. The following table lists all ActionScript keywords: break default extends if instanceof private static var case delete for implements interface public switch void class dynamic function import intrinsic return this while continue else get in new set typeof with Constants A constant is a property whose value never changes. For example, the constants BACKSPACE, ENTER, QUOTE, RETURN, SPACE, and TAB are properties of the Key object and refer to keyboard keys. To test whether the user is pressing the Enter key, you could use the following statement: if(Key.getCode() == Key.ENTER) { alert = "Are you ready to play?"; controlMC.gotoAndStop(5); } Syntax 33 About data types A data type describes the kind of information a variable or ActionScript element can hold. There are two kinds of data types built into Flash: primitive and reference. The primitive data types-- String, Number, and Boolean--have a constant value and therefore can hold the actual value of the element they represent. The reference data types--MovieClip and Object--have values that can change and therefore contain references to the actual value of the element. Variables containing primitive data types behave differently in certain situations than those containing reference types. (See "Using variables in a program" on page 43.) There are also two special data types: null and undefined. In Flash, any built-in object that isn't a primitive data type or a movie clip data type, such as Array or Math, is of the Object data type. Each data type has its own rules and is described in the following topics: · · · · · · · "String" on page 34 "Number" on page 35 "Boolean" on page 35 "Object" on page 36 "MovieClip" on page 36 "Null" on page 36 "Undefined" on page 36 When you debug scripts, you may need to determine the data type of an expression or variable to understand why it is behaving a certain way. You can do this with the typeof operator (see "Determining an item's data type" on page 37). You can convert one data type to another using one of the following conversion functions: Array(), Boolean(), Number(), Object(), String(). String A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single or double quotation marks. Strings are treated as characters instead of as variables. For example, in the following statement, "L7" is a string: favoriteBand = "L7"; You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. The following expression includes a space after the comma: greeting = "Welcome," + firstName; 34 Chapter 2: ActionScript Basics To include a quotation mark in a string, precede it with a backslash character (\). This is called escaping a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table provides all the ActionScript escape characters: Escape sequence \b \f \n \r \t \" \' \\ \000 - \377 \x00 - \xFF \u0000 - \uFFFF Character Backspace character (ASCII 8) Form-feed character (ASCII 12) Line-feed character (ASCII 10) Carriage return character (ASCII 13) Tab character (ASCII 9) Double quotation mark Single quotation mark Backslash A byte specified in octal A byte specified in hexadecimal A 16-bit Unicode character specified in hexadecimal Number The number data type is a double-precision floating-point number. You can manipulate numbers using the arithmetic operators addition (+), subtraction (-), multiplication (*), division (/), modulo (%), increment (++), and decrement (--). You can also use methods of the built-in Math and Number classes to manipulate numbers. The following example uses the sqrt() (square root) method to return the square root of the number 100: Math.sqrt(100); For more information, see "Numeric operators" on page 45. Boolean A Boolean value is one that is either true or false. ActionScript also converts the values true and false to 1 and 0 when appropriate. Boolean values are most often used with logical operators in ActionScript statements that make comparisons to control the flow of a script. For example, in the following script, the SWF file plays if the variable password is true: onClipEvent(enterFrame) { if (userName == true && password == true){ play(); } } See "Using built-in functions" on page 51 and "Logical operators" on page 47. About data types 35 Object An object is a collection of properties. Each property has a name and a value. The value of a property can be any Flash data type, even the object data type. This allows you to arrange objects inside each other, or nest them. To specify objects and their properties, you use the dot (.) operator. For example, in the following code, hoursWorked is a property of weeklyStats, which is a property of employee: employee.weeklyStats.hoursWorked You can use the built-in ActionScript objects to access and manipulate specific kinds of information. For example, the Math object has methods that perform mathematical operations on numbers you pass to them. This example uses the sqrt() method: squareRoot = Math.sqrt(100); The ActionScript MovieClip object has methods that let you control movie clip symbol instances on the Stage. This example uses the play() and nextFrame() methods: mcInstanceName.play(); mc2InstanceName.nextFrame(); You can also create custom objects to organize information in your Flash application. To add interactivity to an application with ActionScript, you'll need many different pieces of information: for example, you might need a user's name, the speed of a ball, the names of items in a shopping cart, the number of frames loaded, the user's ZIP Code, or the key that was pressed last. Creating custom objects lets you organize this information into groups, simplify your scripting, and reuse your scripts. MovieClip Movie clips are symbols that can play animation in a Flash application. They are the only data type that refers to a graphic element. The MovieClip data type allows you to control movie clip symbols using the methods of the MovieClip class. You call the methods using the dot (.) operator, as shown here: my_mc.startDrag(true); parent_mc.getURL("http://www.macromedia.com/support/" + product); Null The null data type has only one value, null. This value means "no value"--that is, a lack of data. The null value can be used in a variety of situations. Here are some examples: · To indicate that a variable has not yet received a value · To indicate that a variable no longer contains a value · As the return value of a function, to indicate that no value was available to be returned by the function · As a parameter to a function, to indicate that a parameter is being omitted Undefined The undefined data type has one value, undefined, and is used for a variable that hasn't been assigned a value. 36 Chapter 2: ActionScript Basics Determining an item's data type While testing and debugging your programs, you may discover problems that seem to be related to the data types of different items. In these cases, you may want to determine an item's data type. To do so, use the typeof operator, as shown in this example: trace(typeof(variableName)); For more information on testing and debugging, see Chapter 3, "Writing and Debugging Scripts," on page 55. Assigning data types to elements Flash automatically assigns data types to the following kinds of language elements, as discussed in the next section, "Automatic data typing": · · · · Variables Parameters passed to a function, method, or class Values returned from a function or method Objects created as subclasses of existing classes However, you can also explicitly assign data types to items, which can help prevent or diagnose certain errors in your scripts. For more information, see "Strict data typing" on page 38. Automatic data typing In Flash, you do not need to explicitly define an item as holding either a number, a string, or other data type. Flash determines the data type of an item when it is assigned: var x = 3; In the expression var x = 3, Flash evaluates the element on the right side of the operator and determines that it is of the number data type. A later assignment may change the type of x; for example, the statement x = "hello" changes the type of x to a string. A variable that hasn't been assigned a value has a type of undefined. ActionScript converts data types automatically when an expression requires it. For example, when you pass a value to the trace() action, trace() automatically converts the value to a string and sends it to the Output panel. In expressions with operators, ActionScript converts data types as needed; for example, when used with a string, the + operator expects the other operand to be a string. "Next in line, number " + 7 ActionScript converts the number 7 to the string "7" and adds it to the end of the first string, resulting in the following string: "Next in line, number 7" Assigning data types to elements 37 Strict data typing ActionScript 2.0 lets you explicitly declare the object type of a variable when you create it; this is called strict data typing. Because data type mismatches trigger compiler errors, strict data typing helps prevent you from assigning the wrong type of data to an existing variable. To assign a specific data type to an item, specify its type using the var keyword and post-colon syntax: // strict typing of variable or object var x:Number = 7; var birthday:Date = new Date(); // strict typing of parameters function welcome(firstName:String, age:Number){ } // strict typing of parameter and return value function square(x:Number):Number { var squared = x*x; return squared; } Because you must use the var keyword when strictly typing variable, you can't strictly type a global variable (see "Scoping and declaring variables" on page 41). You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create. For example, if you have a file named Student.as in which you define the Student class, you can specify that objects you create are of type Student: var student:Student = new Student(); You can also specify that objects are of type Function or Void. Using strict typing helps ensure that you don't inadvertently assign an incorrect type of value to an object. Flash checks for typing mismatch errors at compile time. For example, suppose you type the following code: // in the Student.as class file class Student { var status:Boolean; // property of Student objects } // in a script var studentMaryLago:Student = new Student(); studentMaryLago.status = "enrolled"; When Flash compiles this script, a "Type mismatch" error is generated. Another advantage of strict data typing is that Flash MX 2004 automatically displays code hints for built-in objects when they are strictly typed. For more information, see "Strictly typing objects to trigger code hints" on page 62. Files published using ActionScript 1 do not respect strict data typing assignments at compile time. Thus, assigning the wrong type of value to a variable that you have strictly typed doesn't generate a compiler error. var x:String = "abc" x = 12 ; // no error in ActionScript 1, type mismatch error in ActionScript 2 38 Chapter 2: ActionScript Basics The reason for this is that when you publish a file for ActionScript 1, Flash interprets a statement such as var x:String = "abc" as slash syntax rather than as strict typing. (ActionScript 2.0 doesn't support slash syntax.) This behavior can result in an object that is assigned to a variable of the wrong type, causing the compiler to let illegal method calls and undefined property references pass through unreported. Therefore, if you are implementing strict data typing, make sure you are publishing files for ActionScript 2.0. Casting objects ActionScript 2.0 lets you cast one data type to another. The cast operator that Flash uses takes the form of a function call and is concurrent with explicit coercion, as specified in the ECMA-262 Edition 4 proposal. Casting lets you assert that an object is of a certain type so that when typechecking occurs, the compiler treats the object as having a set of properties that its initial type does not contain. This can be useful, for example, when iterating over an array of objects that might be of differing types. In files published for Flash Player 7 or later, cast statements that fail at runtime return null. In files published for Flash Player 6, no runtime support for failed casts is implemented. The syntax for casting is type(item), where you want the compiler to behave as if the data type of item is type. Casting is essentially a function call, and the function call returns null if the cast fails. If the cast succeeds, the function call returns the original object. However, the compiler doesn't generate type mismatch errors when you cast items to data types that you created in external class files, even if the cast fails at runtime. // in Animal.as class Animal {} // in Dog.as class Dog extends Animal { function bark (){} } // in Cat.as class Cat extends Animal { function meow (){} } // in FLA file var spot:Dog = new Dog(); var temp:Cat = Cat (spot); // assert that a Dog object is of type Cat temp.meow(); // doesn't do anything, but no compiler error either In this situation, you asserted to the compiler that temp is a Cat object, and, therefore, the compiler assumes that temp.meow() is a legal statement. However, the compiler doesn't know that the cast will fail (that is, that you tried to cast a Dog object to a Cat type), so no compile-time error occurs. If you include a check in your script to make sure that the cast succeeds, you can find type mismatch errors at runtime. var spot:Dog = new Dog(); var temp:Cat = Cat (spot); trace(temp); // displays null at runtime You can cast an expression to an interface. If the expression is an object that implements the interface or has a base class that implements the interface, the object is returned. If not, null is returned. Assigning data types to elements 39 The following example shows the results of casting built-in object types. As the first line in the with(results) block shows, an illegal cast--in this case, casting a string to a movie clip-- returns null. As the last two lines show, casting to null or undefined returns undefined. var mc:MovieClip; var arr:Array; var bool:Boolean; var num3:Number; var obj:Object; var str:String; _root.createTextField("results",2,100,100,300,300); with(results){ text = "type MovieClip : "+(typeof MovieClip(str)); text += "\ntype object : "+(typeof Object(str)); text += "\ntype Array : "+(typeof Array(num3)); text += "\ntype Boolean : "+(typeof Boolean(mc)); text += "\ntype String : "+(typeof String(mc)); text += "\ntype Number : "+(typeof Number(obj)); text += "\ntype Function : "+(typeof Function(mc)); text += "\ntype null : "+(typeof null(arr)); text += "\ntype undefined : "+(typeof undefined(obj)); } //Results in Output panel type MovieClip : null type object : object type Array : object type Boolean : boolean type String : string type Number : number type Function : object type null : undefined type undefined : undefined // // // // // // // // // returns returns returns returns returns returns returns returns returns null object object boolean string number object undefined undefined You can't override primitive data types such as Boolean, Date, and Number with a cast operator of the same name. About variables A variable is a container that holds information. The container itself is always the same, but the contents can change. By changing the value of a variable as the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is true or false. It's a good idea always to assign a variable a known value the first time you define the variable. This is known as initializing a variable and is often done in the first frame of the SWF file. Initializing a variable helps you track and compare the variable's value as the SWF file plays. Variables can hold any type of data (see "About data types" on page 34). The type of data a variable contains affects how the variable's value changes when it is assigned in a script. Typical types of information that you can store in a variable include a URL, a user's name, the result of a mathematical operation, the number of times an event occurred, or whether a button has been clicked. Each SWF file and movie clip instance has a set of variables, with each variable having a value independent of variables in other SWF files or movie clips. 40 Chapter 2: ActionScript Basics To test the value of a variable, use the trace() action to send the value to the Output panel. For example, trace(hoursWorked) sends the value of the variable hoursWorked to the Output panel in test mode. You can also check and set the variable values in the Debugger in test mode. For more information, see "Using the trace statement" on page 79 and "Displaying and modifying variables" on page 72. Naming a variable A variable's name must follow these rules: · It must be an identifier (see "Terminology" on page 26). · It cannot be a keyword or an ActionScript literal such as true, false, null, or undefined. · It must be unique within its scope (see "Scoping and declaring variables" on page 41). Also, you should not use any element in the ActionScript language as a variable name; doing so can cause syntax errors or unexpected results. For example, if you name a variable String and then try to create a String object using new String(), the new object is undefined. hello_str = new String(); trace(hello_str.length); // returns 0 String = "hello"; // Giving a variable the same name as a built-in class hello_str = new String(); trace(hello_str.length); // returns undefined The ActionScript editor supports code hints for built-in classes and for variables that are based on these classes. If you want Flash to provide code hints for a particular object type that is assigned to a variable, you can strictly type the variable or name the variable using a specific suffix. For example, suppose you type the following code: var members:Array = new Array(); members. As soon as you type the period (.), Flash displays a list of methods and properties available for Array objects. For more information, see "Writing code that triggers code hints" on page 61. Scoping and declaring variables A variable's scope refers to the area in which the variable is known and can be referenced. There are three types of variable scope in ActionScript: · Local variables are available within the function body in which they are declared (delineated by curly braces). · Timeline variables are available to any script on that Timeline. · Global variables and functions are visible to every Timeline and scope in your document. Note: ActionScript 2.0 classes that you create support public, private, and static variable scopes. For more information, see "Controlling member access" on page 164 and "Creating class members" on page 165. About variables 41 Local variables To declare local variables, use the var statement inside the body of a function. A local variable is scoped to the block and expires at the end of the block. A local variable not declared within a block expires at the end of its script. For example, the variables i and j are often used as loop counters. In the following example, i is used as a local variable; it exists only inside the function makeDays(): function makeDays() { var i; for( i = 0; i < monthArray[month]; i++ ) { _root.Days.attachMovie( "DayDisplay", i, i + 2000 ); _root.Days[i].num = i + 1; _root.Days[i]._x = column * _root.Days[i]._width; _root.Days[i]._y = row * _root.Days[i]._height; column = column + 1; if (column == 7 ) { column = 0; row = row + 1; } } } Local variables can also help prevent name conflicts, which can cause errors in your application. For example, if you use name as a local variable, you could use it to store a user name in one context and a movie clip instance name in another; because these variables would run in separate scopes, there would be no conflict. It's good practice to use local variables in the body of a function so that the function can act as an independent piece of code. A local variable is only changeable within its own block of code. If an expression in a function uses a global variable, something outside the function can change its value, which would change the function. You can assign a data type to a local variable when you define it, which helps prevent you from assigning the wrong type of data to an existing variable. For more information, see "Strict data typing" on page 38. Timeline variables Timeline variables are available to any script on that Timeline. To declare Timeline variables, initialize them on any frame in the Timeline. Be sure to initialize the variable before trying to access it in a script. For example, if you put the code var x = 10; on Frame 20, a script attached to any frame before Frame 20 cannot access that variable. 42 Chapter 2: ActionScript Basics Global variables Global variables and functions are visible to every Timeline and scope in your document. To create a variable with global scope, use the _global identifier before the variable name, and do not use the var = syntax. For example, the following code creates the global variable myName: var _global.myName = "George"; // syntax error _global.myName = "George"; However, if you initialize a local variable with the same name as a global variable, you don't have access to the global variable while you are in the scope of the local variable: _global.counter = 100; counter++; trace(counter); // displays 101 function count(){ for( var counter = 0; counter <= 10 ; counter++ ) { trace(counter); // displays 0 through 10 } } count(); counter++; trace(counter); // displays 102 Using variables in a program You must declare a variable in a script before you can use it in an expression. If you use an undeclared variable, as shown in the following example, the variable's value will be NaN or undefined, and your script might produce unintended results: var squared = x*x; trace(squared); // NaN var x = 6; In the following example, the statement declaring the variable x must come first so that squared can be replaced with a value: var x = 6; var squared = x*x; trace(squared); // 36 Similar behavior occurs when you pass an undefined variable to a method or function: getURL(myWebSite); // no action var myWebSite = "http://www.macromedia.com"; var myWebSite = "http://www.macromedia.com"; getURL(myWebSite); // browser displays www.macromedia.com You can change the value of a variable many times in a script. The type of data that the variable contains affects how and when the variable changes. Primitive data types, such as strings and numbers, are passed by value. This means that the actual content of the variable is passed to the variable. In the following example, x is set to 15 and that value is copied into y. When x is changed to 30 in line 3, the value of y remains 15 because y doesn't look to x for its value; it contains the value of x that it received in line 2. var x = 15; var y = x; var x = 30; About variables 43 As another example, the variable inValue contains a primitive value, 3, so the actual value is passed to the sqrt() function and the returned value is 9: function sqrt(x){ return x * x; } var inValue = 3; var out = sqrt(inValue); The value of the variable inValue does not change. The object data type can contain such a large and complex amount of information that a variable with this type doesn't hold the actual value; it holds a reference to the value. This reference is like an alias that points to the contents of the variable. When the variable needs to know its value, the reference asks for the contents and returns the answer without transferring the value to the variable. The following is an example of passing by reference: var myArray = ["tom", "josie"]; var newArray = myArray; myArray[1] = "jack"; trace(newArray); The above code creates an Array object called myArray that has two elements. The variable newArray is created and is passed a reference to myArray. When the second element of myArray is changed, it affects every variable with a reference to it. The trace() action sends tom, jack to the Output panel. In the following example, myArray contains an Array object, so it is passed to function zeroArray() by reference. The zeroArray() function changes the content of the array in myArray. function zeroArray (theArray){ var i; for (i=0; i < theArray.length; i++) { theArray[i] = 0; } } var myArray = new Array(); myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; zeroArray(myArray); The function zeroArray() accepts an Array object as a parameter and sets all the elements of that array to 0. It can modify the array because the array is passed by reference. 44 Chapter 2: ActionScript Basics Using operators to manipulate values in expressions An expression is any statement that Flash can evaluate and that returns a value. You can create an expression by combining operators and values or by calling a function. Operators are characters that specify how to combine, compare, or modify the values of an expression. The elements that the operator performs on are called operands. For example, in the following statement, the + operator adds the value of a numeric literal to the value of the variable foo; foo and 3 are the operands: foo + 3 This section describes general rules about common types of operators, operator precedence, and operator associativity. For detailed information on each operator mentioned here, as well as special operators that don't fall into these categories, see the entries in Chapter 12, "ActionScript Dictionary," on page 205. Operator precedence and associativity When two or more operators are used in the same statement, some operators take precedence over others. ActionScript follows a precise hierarchy to determine which operators to execute first. For example, multiplication is always performed before addition; however, items in parentheses take precedence over multiplication. So, without parentheses, ActionScript performs the multiplication in the following example first: total = 2 + 4 * 3; The result is 14. But when parentheses surround the addition operation, ActionScript performs the addition first: total = (2 + 4) * 3; The result is 18. When two or more operators share the same precedence, their associativity determines the order in which they are performed. Associativity can be either left-to-right or right-to-left. For example, the multiplication operator has an associativity of left-to-right; therefore, the following two statements are equivalent: total = 2 * 3 * 4; total = (2 * 3) * 4; For a table of all operators and their precedence and associativity, see Appendix B, "Operator Precedence and Associativity," on page 787. Numeric operators Numeric operators add, subtract, multiply, divide, and perform other arithmetic operations. The most common usage of the increment operator is i++ instead of the more verbose i = i+1. You can use the increment operator before or after an operand. In the following example, age is incremented first and then tested against the number 30: if (++age >= 30) In the following example, age is incremented after the test is performed: if (age++ >= 30) Using operators to manipulate values in expressions 45 The following table lists the ActionScript numeric operators: Operator + * / % ++ -- Operation performed Addition Multiplication Division Modulo (remainder of division) Subtraction Increment Decrement Comparison operators Comparison operators compare the values of expressions and return a Boolean value (true or false). These operators are most commonly used in loops and in conditional statements. In the following example, if the variable score is 100, a certain SWF file loads; otherwise, a different SWF file loads: if (score > 100){ loadMovieNum("winner.swf", 5); } else { loadMovieNum("loser.swf", 5); } The following table lists the ActionScript comparison operators: Operator < > <= >= Operation performed Less than Greater than Less than or equal Greater than or equal

If this document matches the user guide, instructions manual or user manual, feature sets, schematics you are looking for, download it now. Diplodocs provides you a fast and easy access to the user manual MACROMEDIA FLASH MX 2004.

MACROMEDIA offer a product for which we do not have the user manual? Let us know what you are looking for: user guide, owner's manual, online manual, operating instructions, quick start guide, mounting instructions, schematics, service manual, installation instructions, RTFM.

Diplodocs allows you to download user manual MACROMEDIA FLASH MX 2004, user guide MACROMEDIA FLASH MX 2004, instructions MACROMEDIA FLASH MX 2004, owner's manual MACROMEDIA FLASH MX 2004, online manual MACROMEDIA FLASH MX 2004.


MACROMEDIA FLASH MX 2004, , Software.
Include the add-on to download manuals from your site, forum or blog Frequently Asked Questions Contact Diplodocs team Last searches
Last additions
Sitemap
Brands starting with A B C D E F G H I J K L M N O P Q R S T U V W X Y Z #
Copyright © 2005 - 2008 - Diplodocs - All Rights Reserved.
Designated trademarks and brands are the property of their respective owners.