Adobe
Productos
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Más productos
Soluciones
Marketing digital
Medios digitales
Educación
Servicios financieros
Administración
Gestión de experiencias web
Más soluciones
Formación Ayuda Descargas Empresa
Comprar
Uso doméstico Para uso personal y autónomos
Educación Para estudiantes, profesores y empleados
Empresas para pequeñas y medianas empresas
Programas multilicencia para empresas, centros educativos y gobiernos
Otras formas de comprar
Ofertas especiales
Búsqueda
 
Información Registro
Bienvenido, Mi carro Mis envíos Asistencia
Mi cuenta
Salir
¿Por qué registrarse? Regístrese para poder gestionar su cuenta y acceder a descargas de prueba, ampliaciones de productos, diferentes áreas de la comunidad y mucho más.
Adobe
Productos Secciones Comprar   Búsqueda  
Soluciones Empresa
Ayuda Aprendizaje
Registro Salir Mis envíos Asistencia
Date Date
Qty:
Subtotal
Checkout
Adobe Developer Connection / Centro de desarrollo de Flash /

Situations to avoid when writing ActionScript

por Tommi West

Tommi West
  • tommiland.com

Content

  • Missing instance names causes code errors
  • Importance of adhering to naming conventions
  • Watch out for case sensitivity in ActionScript 3
  • Accidentally entering instance names in the frame label field
  • Inconsistent use of prefixes, suffixes, camel case, or switching between underscores and dashes
  • Invalid code references and missing syntax
  • Broken links to external linked assets
  • Providing the wrong path in HTML object tags
  • Avoiding endless loops
  • Customizing third-party code
  • Never mix ActionScript 2 and ActionScript 3 code in the same project
  • Choose the correct version of ActionScript when creating new files
  • Use even numbers to make math easier
  • Use frame labels rather than hard-coding frame numbers
  • Preventing ActionScript runtime and compiler errors
  • Where to go from here

Created

16 January 2012

Herramientas de página

Compartir en Facebook
Compartir en Twitter
Compartir en LinkedIn
Marcar como favorito
Imprimir

Tags

Requisitos

Conocimientos previos

Previous experience working with Flash Professional is recommended. Refer to Avoiding common authoring mistakes to find links to other articles in this series.

Nivel de usuario

Todos

Productos necesarios

  • Flash Professional (Download trial)

Follow these development tips and best practices when developing Adobe Flash Professional projects with ActionScript. This list includes common mistakes that may cause runtime errors or problems that require code debugging. By following these recommendations, you can save time and make your code more extensible.

Missing instance names causes code errors

If you follow a consistent workflow, such as always naming instances as soon as they are added to the Stage, you can eliminate issues that occur when code references cannot find matching instance names (such as undefined errors).

Importance of adhering to naming conventions

If you get in the habit of naming instances consistently, you'll save time and make the code easier for other developers to update. It's important to choose a naming convention (such as adding a mc_ prefix or a _mc suffix to movie clip instance names) and standardize the names you enter in the instance name field. If you are naming a set of symbol instances that are used to animate a complex object, you may also find it helpful to name the items in a set with the object's name and then the description, like this:

  • dog_mouth_mc
  • dog_nose_mc
  • dog_tail_mc

This practice helps eliminate typos in the project and makes the code easier to understand.

To learn more, read Naming conventions in ActionScript on the Flash Valley site. Also check out the Syntax and Variables sections of the "ActionScript 3 fundamentals" series on the Adobe Developer Connection to learn more about naming conventions.

Additionally, it is critical to avoid using reserved words or beginning instance names with numbers, because these habits can result in programming issues. See the list of reserved words from the O'Reilly book, ActionScript: The Definitive Guide.

Watch out for case sensitivity in ActionScript 3

ActionScript 3.0 is a case-sensitive language. Identifiers that use lower case instead of upper case are considered different identifiers. For example, the following code creates two different variables in the same script:

var num1:int; var Num1:int;

The general convention is that class names should begin with a capital letter. Usually, all other names (such as functions, instances, and variables) start with a lowercase letter. If names contain multiple words, all words after the first word in a name can be capitalized (to use camel case for legibility).

Accidentally entering instance names in the frame label field

While entering instance names, verify that you are typing into the Instance Name field in the Property inspector. If you select an instance by clicking a keyframe in the Timeline, it is a common mistake to accidentally enter its instance name in the Frame Label field instead (see Figure 1).

Figure 1. Always click the instance on the Stage to ensure you enter the instance name in the Instance Name field in the Property inspector.
Figure 1. Always click the instance on the Stage to ensure you enter the instance name in the Instance Name field in the Property inspector.

Inconsistent use of prefixes, suffixes, camel case, or switching between underscores and dashes

Many developers add a short notation in their instance names to define them in the code, such as naming movie clips with a mc_ prefix, buttons with a btn_ prefix, and graphic symbols with a gfx_ prefix. You could alternately choose to add suffixes instead, such as naming movie clips with a _mc suffix, buttons with a _btn suffix, and graphic symbols with a _gfx suffix.

You could also choose to capitalize the second word in an instance's name, like this: leftEye_mc and rightEye_mc. This second word capitalization is known as "camel case" because the capital character creates a hump in the middle of the name.

All of these naming conventions are valid. However, it's important to choose one tactic and stick to it for the entire project, to avoid confusion and typos.

Additonally, you can use either underscores or dashes to separate words in a name, such as dog_head or dog-head. You'll find you make less mistakes if you make a conscious decision to always use one or the other, rather than alternating between both in a project.

By choosing your favorite method and standardizing the names you apply to instances, you'll be less likely to encounter errors. This helps eliminate the time-consuming task of scanning the code looking for the mismatch between underscores and dashes.

Invalid code references and missing syntax

Take care when writing code to properly reference the names of instances in your project. In addition to avoiding the instance names pitfalls listed above, type carefully to reduce the possibility of introducing typos in properties, events, or methods that can cause runtime errors. For example, when typing the play() method, be sure to add both opening and closing parenthesis. Also watch out for missing quotes and semicolons.

You may find it helpful to click the Check Syntax button (the blue check mark above the Script pane) to make sure there are no syntax errors in the code. Click this option frequently as you add new code. If syntax errors are detected, they are displayed in the Output panel when you test the movie.

Note: It's important to remember that when you check syntax, only the current script in the Actions panel is checked; other scripts that may linked to the FLA file are not checked.

Broken links to external linked assets

It is often desireable to link your project to external assets. This strategy can make the Flash movie easier to manage and update. However, take care that the paths to the external scripts and graphic elements are correct. If you provide an invalid path to the file, you'll receive an error when you run the SWF file.

Also be careful not to introduce typographical errors when referencing the name of the file. Whenever possible, compare the actual file's name at the time you enter it in Flash to make sure it is spelled correctly.

To learn more, read Loading images and Library assets with ActionScript 3 on the Adobe Developer Connection.

Note: Also be careful to avoid other activities that could cause paths to break, such as moving content to another computer or server or deleting dependent files entirely.

Providing the wrong path in HTML object tags

If you choose the option to create an HTML wrapper file in the Publish settings and then publish your project, the resulting files include a folder with the SWF file and the HTML file that contains the code the browser uses to display the SWF file. By default, both the HTML file and the SWF file are exported to the same directory.

Be aware that if you move the HTML file or the SWF file out of the directory where it was generated, the path in the HTML code that links to the SWF file will break. The path will also break if you rename the SWF file. Always test the published movie locally and update the path to the SWF file as needed before uploading the HTML and SWF file to the host server (see Figure 2).

Figure 2. After publishing, both the HTML and SWF files are saved in the same folder alongside the FLA file.
Figure 2. After publishing, both the HTML and SWF files are saved in the same folder alongside the FLA file.

Avoiding endless loops

Even if you don't use the loop keyword in your scripts, it is possible to accidentally create code that loops endlessly. Take care to avoid writing infinite loops in functions, because they can crash Flash Player and consume system resources. The while loop example below will continually trace the value of the i variable, which will result in the Output panel displaying an endless series of zeros:

var i:int = 0; while (i < 5) { trace(i); }

To update this loop so that it resolves after a period of iterations, rather than being endless, add the following line of code below the trace statement inside the curly braces:

i++;

After adding this line of code, the value of the variable " i " is incremented, so that the while loop outputs the values 0, 1, 2, 3, 4 and then stops when the < operator compares the value of i and finds that it has become equal to (not less than) 5. Always add a conditional statement to loops. When the condition is met (or is true), the code stops looping.

To learn more about writing loops in ActionScript 3, see the Scripted Loops article on ActionScript.org. Also read the Loops section of the "ActionScript 3 fundamentals" series on the Adobe Developer Connection.

Customizing third-party code

Take care when repurposing third-party code to enter all of the necessary parameters. Follow these guidelines when using code written by someone else:

  • ActionScript version: Use ActionScript 3 code when creating an ActionScript 3 project.
  • Instance names: Update instance names to match the names of instances in your project.
  • External links: Verify that the code snippet does not require other external scripts.
  • Attribution: Always leave in comments that identify the original author of the code.

Never mix ActionScript 2 and ActionScript 3 code in the same project

When you create or publish Flash projects, you are prompted to choose the version of ActionScript that the player will interpret. You can either choose ActionScript 3 or ActionScript 2, but not both. If your project contains both types of code, it is likely that the project will have issues when you attempt to run it, because the interpreter will process only a portion of the scripts.

Be especially careful when incorporating third-party code into your projects. Always verify which version of ActionScript a code snippet uses before adding it, to avoid confusion.

Choose the correct version of ActionScript when creating new files

When you choose File > New, be sure to select ActionScript 3 as the version in the New Document dialog box when you are developing ActionScript 3 projects. Conversely, if you are using ActionScript 2, be sure to choose that option at the time you create the file (see Figure 3).

Figure 3. Select the version of ActionScript you'll be using for each new project.
Figure 3. Select the version of ActionScript you'll be using for each new project.

Note: When repurposing code from online tutorials and third-party sources, be sure to verify that the ActionScript version matches the version used in your project to avoid mixing ActionScript 2 and ActionScript 3 code in the same FLA file.

Use even numbers to make math easier

Whenever possible, strive to use even values (numbers divisible by two); for instance, dimensions, Stage size, and spacing of elements. This strategy helps keep your code clean and makes it much easier to calculate values when creating functions.

Use frame labels rather than hard-coding frame numbers

Although it may be tempting to specify a location in the Timeline by its frame number, it is a best practice to create a frame label and reference that location by its frame label name instead. This strategy prevents issues that may occur later when additional frames are added or removed from the Timeline. If you add frame labels, the label names will not change even if the number of frames in the Timeline are adjusted for a project. Additionally, using frame labels as references rather than frame numbers makes the code easier to read.

Here's an example of correct usage of a frame label:

function goDemo(event:MouseEvent):void { demo_btn.gotoAndPlay("demo"); }

And here's an example of incorrectly specifying a frame number: 

function goDemo(event:MouseEvent):void { demo_btn.gotoAndPlay(10); }

To read more about frame labels, see the Frame label section of the Flash Glossary.

Preventing ActionScript runtime and compiler errors

The Output window will display a numeric error number and message if you test a movie that contains runtime errors or compiler errors. These errors often occur when Flash Player is unable to find an object that is referenced or when the code syntax contains errors, including typographical errors or missing symbols, such as parenthesis.

For more details, read the recommendations for fixing runtime and compiler errors on Senocular.com.

Where to go from here

To learn more about programming Flash projects with ActionScript, see the following resources:

  • ActionScript Technology Center
  • Learning ActionScript 3
  • ActionScript 3 reference for the Adobe Flash Platform

Refer to Avoiding common authoring mistakes to find links to other articles in this series.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License

More Like This

  • Flash glossary: Actions panel
  • Flash glossary: Frame label
  • Flash glossary: Buttons
  • Flash glossary: Scope
  • Five demos of Flash CS4 Professional
  • Working with the Project panel in Flash Professional CS5.5
  • Flash glossary: Code snippets
  • Flash glossary: Export for ActionScript
  • Flash glossary: Class
  • Understanding ActionScript 3 debugging in Flash

Productos

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile apps
  • Photoshop
  • Touch Apps

Soluciones

  • Marketing digital
  • Medios digitales
  • Gestión de experiencias web

Sectores

  • Educación
  • Servicios financieros
  • Administración

Ayuda

  • Centros de soporte de productos
  • Pedidos y devoluciones
  • Descarga e instalación
  • Mi Adobe

Aprendizaje

  • Adobe Developer Connection
  • Adobe TV
  • Formación y certificación
  • Foros
  • Centro de diseño

Formas de comprar

  • Para uso personal y autónomos
  • Para estudiantes, profesores y empleados
  • Para estudiantes, profesores y empleados
  • Para empresas, centros educativos y gobiernos
  • Ofertas especiales

Descargas

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Empresa

  • Sala de noticias
  • Programas de socios
  • Responsabilidad social corporativa
  • Oportunidades laborales
  • Relaciones con los inversores
  • Actos
  • Jurídico
  • Seguridad
  • Contactar con Adobe
Seleccionar región España (Cambiar)
Seleccionar región Cerrar

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Condiciones de uso | Política de privacidad y cookies (Actualizado)