Home  >  

LFFS - 4: ActionScript 3.0

AddThis Social Bookmark Button
As promised, the current installment of Learning Flex From Scratch focuses on the syntax of ActionScript 3.0. We know from the previous post that an application written in an object-oriented programming language involves, by definition, the use of objects. Objects, we found out, are derived from classes, which serve as a blueprint for the object's methods and properties. This post goes into the details of creating a class in ActionScript 3.0, providing a foundation for our journey into the language. The code examples provided here are strictly theoretical, and shouldn't be thought of as a working piece of software, but rather as a starting point to illustrate some basic language concepts.

ActionScript shares its lineage with a number of other languages, such as JavaScript, and JScript .NET. This is because these languages are all based on the ECMA-262 fourth edition language specification, and more specifically, ECMAScript. This language specification, developed by ECMA International, is currently under development as of March 2008, and is expected to be finalized in December 2008. By analyzing our theoretical class, we will be learning about many of ActionScript's keywords, rules of syntax, and guidelines for best practices.

The code in the following example is an example of a theoretical construction of a class named Bicycle. Within the class definition are some of the various methods and properties you'd expect a bicycle to have. If you wanted to write an application in ActionScript that involved bicycles, you would of course have to define what bicycles are and what they do. But that wouldn't be enough. You'd also need to define classes for all of the parts of a bicycle that are referred to, (as well as any other objects you'd like to include that relate to these objects), and declare their properties and methods as well. A working program about bicycles would have several classes, all working in concert to provide a logical representation of whatever the programmer intended to demonstrate. We will be discussing the construction of a fully working program in future installments, but for now our focus is on learning the foundations of the language through the examination of a class. Let's begin.

Comments

The first thing we run across in our code example is a series of comments. Comments are statements left by the programmer that won't get compiled as part of the application, but are used to help keep the code organized. It's considered good form to make use of comments so that your code can be followed more easily by others, and so that a potentially large amount of source code remains easy to navigate. According to the language specification, there are three types of comments used in ActionScript 3.0. For comments placed before a method, property, or class definition, the best practice is to use "/**" to start your comment and "*/" to finish it. For comments within a method, there are two accepted versions depending on the length of the comment. One line comments begin with "//". In fact, "//" literally means ignore everything after "//" until the next line. The "//" can occur at the beginning or the end of a line of source code. For comments within a method that spans multiple lines, you use this set of operators:

"/*"[Comment]" */".
Package Declaration

A package declaration is the first part of an ActionScript class. It looks like: package com.mycompany.myapplication, followed on the next line by an opening curly brace. This is a package declaration. A package is a conceptual container in which we can put our class declaration. You can legally declare a class (meaning it would be within the rules of ActionScript) without putting it in a package, but it's considered a best practice to use one. There are a few reasons why this is important. One reason for the use of packages is that a class name should ideally be unique within a program. One way to ensure this is by using a variation of a uniform resource locator (URL). In our example we use the reversed "com.mycompany.myapplication" URL as our unique name. Maintaining your classes within a uniquely named package allows you to more safely share code with other programmers. In the event that another programmer has created a class that has the same name as one in your application, you can still use that class without conflict if it's wrapped in a package. Classes take on their package name as part of their identity, and are thus guaranteed to be unique.

Objects derived from classes within a package have access to only those objects within that package by default. In the event that you need to grant access to an object that's outside the package, you use the "import" keyword. You can choose to import the entire package, or just the class you need from the package. For example, if you would like to work with the flash MovieClip class within your package you would type:
import flash.display.MovieClip;

Following the package declaration, we have the opening curly brace that marks the beginning of the content of our package.

Class Declaration
The next piece of code that we run across is our class declaration.
public class Bicycle
This is our declaration of the Bicycle class. By convention, class names are capitalized. If we had a banana seat bike class, then our class would be called BananaSeatBicycle . This kind of notation is called "camel case". The "class" keyword alerts the compiler to the fact that a class definition is on its way. By declaring the class "public" we are saying that code within this class may be accessed by code from another class. Next, we can see that, like our package declaration, our class definition has an opening curly brace. It is in between this opening brace and its subsequent closing brace that the class' body is located. The class body contains all of the methods, properties, and variables that belong to the class; in other words, its members.

The Constructor Method

Next, we see another comment, this one announcing the presence of a constructor method.
/**
* This is the constructor method, and it is always "public".
*/
public function Bicycle( seatHeight : int = 0,
                                     typeOfBicycle : String = null,
                                     totalWeight : int = 0,
                                     currentGear : int = 0)

A constructor method, or simply constructor, is the set of instructions that are executed when an instance of a class is created (i.e. instantiated). As the comment lets us know, a constructor method is always public in ActionScript (but not in all OO languages). The compiler knows that it's a constructor method because the name of the method (Bicycle) is also the name of the class. Method declarations in ActionScript are written using the "function" keyword followed by the name of the function. Following the function name is a set of parentheses. It is within these parentheses that a method can hold additional information in the form of method parameters.

In our example, the method parameters are: seatHeight, typeOfBicycle, totalWeight, and currentGear. Each of these parameters holds a certain type of data. In the case of seatHeight, we know the height of the seat is expressed by a whole number, and its default is 0. Our "typeOfBicycle" parameter is represented by data of String type. Possible candidates for a String value for this parameter might be: "road", "mountain", or "recumbent".

A constructor's parameter is a special type of local variable. A local variable is a special type of variable (a representation of data in memory) that is used to represent data within a method. Local variables can only be accessed within the method in which they are defined, hence the term "local". In addition, local variables can only be used as long as the method in which they are defined is executing. When we refer to the area of an application in which a method, variable, or property "lives", we are speaking of that member's scope. Also, the time during which a variable is available is called it's lifetime. We'll talk more about scope and lifetime in subsequent posts.

Our parameter names are followed by a ":" operator which is then followed by the data type and the variable's initial value. In ActionScript, and in other languages as well, the use of the ":" operator tells us that the term before it "is" one of whatever term follows it. For example, seatHeight : int = 0 means that the variable seatHeight is of the type int and initially equal to zero.

In all, the first part of our constructor method tells us that for every instance of the Bicycle class, a space in memory is allocated for data represented by the local variables: seatHeight, typeOfBicycle, totalWeight, and currentGear. Because of the the way we have written our class, the values for each local variable could be supplied via the Constructor invocation or set directly on the properties of the object. Because local variables are only active as long as the method in which they have been defined is executing, we must do something more to ensure that the instance of our Bicycle object maintains a reference and/or copy of the data we'd like to save.

The following code exists within the constructor method body:

{
     this.seatHeight = seatHeight;
     this.typeOfBicycle = typeOfBicycle;
     this.totalWeight = totalWeight;
     this.currentGear = currentGear;
}

It tells us that this instance of the Bicycle class has allocated space in memory for data related to "seatHeight", "typeOfBicycle", "totalWeight", and "currentGear". The "this" keyword, followed by a ".", is used to signify the current object, in this case, the instantiated bicycle. It also tells us that these four variables are equal to the supplied initial values.

Properties

The next stop on our "tour de code" is a declaration of the Bicycle class' properties:
/**
* The following are the properties of a Bicycle in the Bicycle class.
*/
public var seatHeight : int = 0;
public var typeOfBicycle : String = null;
public var totalWeight : int = 0;
public var currentGear : int = 0;

As you know, a class' properties are the descriptive data that are bundled within it. To declare a class property, we use the keyword "var" followed by the variable name and class name combination (like in the method parameter declaration), and followed then by the data type and value. We also declare the type of access the application may have on the property by using an access modifier. As is evident in the example, the properties of the Bicycle class are publicly accessible.

Variables

Moving down farther, we come across a comment that alerts us to the fact that the Bicycle class' variables are declared next.
/**
* The variables of Bicycle.
*/
private var numberOfWheels : int = 2;
private var frame : Frame = new Frame();
private var handleBars : HandleBars = new HandleBars();

In the sense of an object, a variable is data that shared between the methods of an object, but encapsulated from access by external objects. In ActionScript we define variables using the keywords "private" and "var", however, a property can also be defined with the "var" keyword. It is considered a property, and not a variable, because the keyword "public" gives it public access. Properties may also be defined using accessor methods. Something we'll look at in later posts.

A variable is simply a name that refers to a specific place in a computer's memory. A variable can have a value associated with it, and it is the variable's value that is returned when an application references a variable. A variable's value can be any sort of data, such as a whole number (int), or group of numbers or symbols (String), or even simply whether something is true or false (Boolean). One particular style of data that a variable can refer to is known as a primitive data type. There are several primitive data types that variables can represent, but to keep it simple, we'll focus on the types of data that are referred to in our Bicycle class: int and String. We also have some custom object types like HandleBars.

Any variable that contains data that can be expressed as a whole number is of the "int" data type. The keyword "int" is what's known as a primitive data type as defined by the language specification. Data of type int refers to some whole number between -2,147,483,648 to 2,147,483,647. Our Bicycle class has several examples of variables that use the int data type, including: "numberOfWheels", "currentGear", etc. It's important to note that operations on a variable must stay consistent with that variable's data type. In the case of "int", by operations we mean tasks like addition, subtraction, multiplication, and division.

To store information that is expressed as a collection of symbols, we use the data type String. Data that is a String (also a primitive data type), is written within quotes, such as: "thisIsAString". Any operation on data of String type returns a String. If a variable is said to be of String data type but is not assigned a value, the default value "null" is applied.

Finally, our Bicycle class has two custom-data types: "Frame", and "HandleBars". These two custom data types suggest that the variables known as "frame" and "handlebars" are of type "Frame" and HandleBars". You'll notice that "frame" and "handlebars" are both initialized where they're declared.

Besides being clued in by the comments, we can tell that the above code contains variables if we know a little about the naming conventions of ActionScript 3.0. A variable is declared by first setting its access to private, and then using the "var" keyword followed by the variable's name. Individual statements in ActionScript that don't include a block (additional instructions contained within curly braces), end in a semi-colon ";". Variable names, as a matter of style, start with a lower case letter, and then capitalize every subsequent word. Additionally, a variable declaration can include the data type, and possibly the initial value of the variable, as is the case with our example.

Methods<br/>
After the Bicycle class' variable declarations, the methods of the class are declared.

/**
* The following are the methods of Bicycle.
*/
public function moveForward(distance:int=0):void {}
public function switchGear(selectedGear:int=0):void {}
public function stopAfterDistanceTraveled(distance:int=0):void {}

Just like the class' constructor method, these methods are declared by using the "function" keyword, followed by the method name, parameters, data types, and value. The methods listed here are of a special type known as instance methods. An instance method's scope is the instance of the class in which it is called. Having been declared public, these methods would welcome code from outside the class to assign values to their local variables. In our example, the local variables "distance" and "selectedGear" would receive values of type int, and Gear, respectively. Since our instance methods have a scope of the current instantiation of the Bicycle class, when outside code assigns a value to their local variable, it affects only this bicycle, and not every bicycle in the application.

As previously mentioned, the code in our current example is an example of a single class, and shouldn't be thought of as a working application on its own. Future installments will go further into explaining the development of an application by explaining how classes interact with each other, and how to execute the code that we've written in our class. In the next few posts, we'll explain the roll of looping functions, conditionals, inherited classes, and interfaces within an application.

The Bicycle Class Definition

/**
* This syntax is used
* for comments before methods, properties, and
* class declarations.
*/

// This syntax is used for comments
// inside a method body that fit on one line.

/* This syntax is used for multi-line
   comments inside a method body. This type
   of comment, as well as single-line
   comments, are ignored by the compiler.
   It's a good idea to make liberal use of
   comments so that your code is easier to
   follow and navigate through. */

package com.mycompany.myapplication
{
 
     public class Bicycle
     {
          /**
           * This is the constructor method, and it is always "public".
           */
          public function Bicycle( seatHeight : int = 0,
                                                typeOfBicycle : String = null,ᅠ
                                               totalWeight : int = 0,ᅠ
                                               currentGear : int = 0 )
          {
               this.seatHeight = seatHeight;
               this.typeOfBicycle = typeOfBicycle;
               this.totalWeight = totalWeight;
               this.currentGear = currentGear;
           }
          /**
           * The following are the properties of a Bicycle in the Bicycle class.
           */
          public var seatHeight : int = 0;
          public var typeOfBicycle : String = null;
          public var totalWeight : int = 0;
          public var currentGear : int = 0;ᅠ
  
          /**
           * The variables of Bicycle.
           */
          private var numberOfWheels : int = 2;
          private var frame : Frame = new Frame();
          private var handleBars : HandleBars = new HandleBars();
  
          /**
           * The following are the methods of Bicycle.
           */
            public function moveForward(distance:int=0):void {}
            public function switchGear(selectedGear:int=0):void {}
            public function stopAfterDistanceTraveled(distance:int=0):void {}
      }
}

Glossary of Terms

// The symbols in ActionScript that signal the beginning of a single line comment.
/* */ Symbols in ActionScript that surround a multi-line comment.
:A symbol ActionScript uses as part of a variable declaration that separates a variables name from it's type.

Application A computer programᅠ

Attribute In ActionScript 3.0, an attribute is any member of a class that is a variable or is defined by a getter or setter method. examples include:
public, private, protected, static, internal, and UserDefinedNamespace.

Best Practices Rules of convention that, when followed, produce elegant code.

Block Statement A collection of directives located within curly braces.

Body In ActionScript, the instructions for classes and its members that are placed within curly braces.

Comment Text within source code that is not read by the compiler, and is there for the purpose of maintaining organization and providing clarity.

Constructor See "Constructor Method".

Constructor Method A specific method within a class that defines the instantiation of an object from the class. Constructor methods are always declared public, and are named after their class.

Custom Data Type See "Object Data Type".

Data Type The specific category in which a variable's data resides. A whole number, for example, is a different data type (int) than a word (String).

Declare The act of including in your source code the methods, properties, parameters, classes, etc that belong to a class.

ECMA-262 The language specification outlined by ECMA International that determines the syntax and rules of best practices of ActionScript 3.0.

ECMA International The international private standards organization that created ECMA-262, and thus ECMAScript.

ECMAScript The scripting language created by ECMA International and defined by the ECMA-262 specification from which ActionScript 3.0 was modeled.

Function A set of instructions to be carried out by a program. In ActionScript are two types of functions: methods, and function closures. A method is a function defined within a class definition, or attached to an object, and a function closure is defined anywhere else.

Import An ActionScript keyword that is used to bring a class declaration into another package.

Instance Methods Methods of a class whose scope is a particular instance of that class.

int A keyword in ActionScript that defines a variable's data type as being a whole number.

JavaScript A scripting language originally developed by Brendan Eich of Netscape. JavaScript was the first dialect of the ECMA-262 specification.

JScript.NET Scripting language developed by Microsoft that, like ActionScript, follows the ECMA-262 language specification.

Keyword Those words that are reserved by the language and that alert the compiler about some important information. For example, the "new" keyword signals the compiler that an object is being instantiated.

Legal The term used to refer to source code that will compile without errors.

Local Variable A variable who's scope includes a specific part of an application.

Main Class A program's point of entry. Always declared public, the main class allows the compiler to access the rest of the program.

Method Parameters Local variables that are included as a part of a method definition.

null A data type that has only one value; null, or "no value". null is the default value for variables of String data type, as well as complex data types such as the Object data type.

Object Data Type A data type that all complex data types stem from.

Operand A value that an operator uses as input.

Operator A function that uses one or more operands together to return a value. Such as: 2 + 2 = 4.

Package A conceptual container in which to place an applications related classes. A class within a package takes on the package name as part of its name and therefore creates a unique namespace for the class to reside in.

Primitive Data Type Special data types specified by the language used to represent variables of type: int, Boolean, String, null, Number, uint, and void.

Scope The part of an application that is accessible to the members of a class.

Statement A basic program instruction or directive.

Static In ActionScript, methods and variables declared as static are accessible at the class level only.

String A primitive data type that represents values expressed in textual form, such as a string of letters in a word.

Syntax The grammatical and structural rules governing the use of symbols and terms within source code.

this A keyword in ActionScript that is used to refer to the current instance of a class.

Uniform Resource Locator (URL) A compact string of characters that are used to locate documents on the web. Guaranteed unique by the World Wide Web Consortium, URLs make good candidates for package names, which require unique identities.

Value The specific data associated with a variable.

var The keyword that tells the compiler to reserve space in memory for a value. In other words, it cues the declaration of a variable.

W3C The World Wide Web Consortium. The main international standards commission for the world wide web.

Next: LFFS - 5: ActionScript 3.0 - Conditionals and Loops

Read more from Adam Flater & Scott Sheridan. Adam Flater & Scott Sheridan's Atom feed

Comments

6 Comments

Peter Martin said:

great series of articles to all learning OO principles and actionscript.
keep it up

Scott said:

@Peter Martin

Thanks Peter! Our plan for the next few installments is to keep it a little shorter/more focused. We'll be checking out the role loops play next. Thanks for reading!

Hyrum Tanner said:

This syntax

public function moveForward( distance : int )= 0 {}

doesn't look right to me. What exactly is that function doing? Did you mean to put

public function moveForward(distance:int = 0):void {}

?

Scott said:

@Hyrum:

You're correct Hyrum, and we apologize for the error. We're working at make the correction, and we appreciate the observation!

Scott said:

(making) ;)

Anonymous said:

//class MouseUtils
package alternativa.utils
{
import flash.display.*;
import flash.geom.*;

public class MouseUtils extends Object
{
public function MouseUtils()
{
super();
return;
}

public static function init(globalToLocal:flash.display.Stage):void
{
var loc1:*;

_stage = loc1;
return;
}

public static function localCoords(stageWidth:flash.display.DisplayObject):flash.geom.Point
{
var loc1:*;

return loc1.globalToLocal(globalCoords());
}

public static function globalCoords(Object:Boolean=true):flash.geom.Point
{
var loc1:*;
var loc2:*;
var loc3:*;
var loc4:*;

loc3 = 0;
loc4 = 0;
loc2 = null;
if (_stage == null)
{
throw new Error("MouseUtility don\'t have link to stage. Use MouseUtility.init(stage) before.");
}
else
{
loc3 = _stage.mouseX;
loc4 = _stage.mouseY;
if (loc1)
{
loc3 = (loc3 _stage.stageWidth) ? _stage.stageWidth : loc3;
loc4 = (loc4 _stage.stageHeight) ? _stage.stageHeight : loc4;
}
loc2 = new Point(loc3, loc4);
}
return loc2;
}


{
_stage = null;
}

private static var _stage:flash.display.Stage=null;
}
}

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.