What Classes Are and Why They're Useful
ActionScript classes allow you to perform all sorts of interactive tasks with Flash. They provide a means for you to work with text, sound, color, dates, and more in very dynamic ways.
As you'll soon learn, ActionScript classes, while intangible, are very much like objects in the real world. They have characteristics known as properties, which can be changed with a script, and they have abilities, known as methods, which allow them to perform various tasks. We'll discuss both of the aspects of objects in depth in a moment.
The primary benefit of using classes in ActionScript is that they allow you to program and manipulate data, colors, sound, dates, and so on in a context that makes sense to humanswe're all familiar with the idea of things having characteristics and abilities.
Understanding the Concept of Classes and Instances
At the introduction of this lesson, we introduced the term class. You are probably wondering what in the world it means. It's actually a simple yet important concept to understand in the world of object-oriented programming. We'll touch on it briefly here to acquaint you with its meaning. A more in-depth discussion can be found in Lesson 6, "Custom Classes," where you'll create your own custom classes.
Class is an organizational phrase used to denote sets of objects with similar characteristics and abilities. You've probably heard the terms upper class, middle class, or working class to describe groups of people that fit a certain mold due to their finances or capabilities. The same general idea applies to the concept of classes in ActionScript. Each object you use in ActionScript belongs to a specific class that defines the general characteristics and abilities of the objects in it. To help you grasp this concept in the realm of ActionScript, let's look at an example.
Perhaps you've noticed that all movie clip instances you place in your project have a _width or _alpha property (among a lot of other common properties), or that you can control every movie clip instance's Timeline using the gotoAndPlay() action (also known as a method). This is because Flash contains a MovieClip class (it's hidden from you, but it exists). This class defines the general capabilities of every movie clip instance you use in your project. Although each movie clip instance might look different, they all have the same basic properties and abilities. This is similar to how humans walk, talk, and sneeze (common abilities), but each human's way of doing it is unique. We are all part of the Human class, so to speak.
It's important to realize that when building your Flash projects, you create and use instances of various classes instead of placing the actual class in your project. It's a subtle but important distinction.
For example, when you drag a movie clip onto the stage, you're actually creating an instance of the MovieClip class. When you create a dynamic text field, you're creating an instance of the TextField class. You will usually work with instances (also known simply as objects) in Flash, as opposed to the actual class (although this can be done, and you will learn how in Lesson 6, "Custom Classes"). A class is often referred to as a blueprint, whereas an instance of that class is thought of as the resulting usable object that you work with, based on that blueprint.
As we mentioned, classes of objects are defined by two primary characteristics: their properties and methods. Let's take an in-depth look at both.
In the discussion that follows, the term object refers to an instance of a class. For example, if we mention an object named mySound, we are referring to an instance of the Sound class named mySound.
Many but not all classes of objects have propertiesvalues that represent characteristics belonging to instances of that class. In the real world, a car has properties such as color, make, model, and horsepower. If your project had a Car class and you had created an instance of it named myCar, you might access the value of its properties in this manner:
var carColor:String = myCar.color; var carTopSpeed:Number = myCar.topSpeed;
Most classes in Flash have properties. For example, instances of the MovieClip class have property values that represent their transparency, visibility, horizontal position, vertical position, and rotation. Changes to any of these properties affect the movie clip instance's appearance or functionality, just as giving a car a paint job or changing its engine would alter the car. You can use property values of various objects in your scripts to set values elsewhere. Assume that a script in your project moves your car at a speed based on its horsepower. That line of script might look like this:
var speedFactor:Number = myCar.horsepower;
Here, the value of speedFactor is dependent on the value of the horsepower property of myCar.
Let's look at one more example of a property and how it's used in ActionScript.
The length of a string is a property of a String class. For example, the length of the term "Flash" is 5 because it contains five characters. In ActionScript, this would be written like this:
var name:String = "Flash"; var lengthOfName:Number = name.length;
The first line of code creates a variable called name whose value is the string "Flash". The second line creates a variable called lengthOfName whose value is that of the length property of the name object (5). Although property names associated with movie clips are usually preceded by an underscore (_alpha and _rotation, for example), the property names of most objects are not preceded by an underscore. MovieClip properties break from what is considered the norm because their properties were first introduced in Flash 4, when ActionScript had a much different form than it has today.
A method represents a task that instances of a class can perform. If you think of VCRs as a class, methods of that class would include the abilities to play, record, stop, rewind, fast forward, and pause. The syntax representing the methods of our VCR class would look like this:
play(); rewind(); record();
For an instance of the VCR class to invoke (use) a method of its class, the syntax requires that you first indicate the name of the VCR class instance, followed by a dot and the name of the method:
This tells the VCR instance named myVCR to start recording.
The parentheses included with the method sometimes allow you to invoke the method in a unique way by using a parameter or set of parameter values. Using the VCR example again, let's say you wanted to record a TV show on Channel 8 from 10:00 p.m. to 11:00 p.m. on September 9. The script required to perform this task might look like this:
myVCR.record("8", "10:00 pm", "11:00 pm", "September 9");
Commas separate the method parameters. Keep in mind that parameter values can be hard coded as shown, or they can be dynamic values such as variables. You can even use other methods as parameters. Although many ActionScript classes have methods that accept parameters, not all do. Some methods simply perform tasks that don't require special settings. For example, the stop() method of the MovieClip class allows you to stop the playback of a movie clip instancenothing more, nothing less, thus additional parameters are unnecessary.
Each class has a unique set of methods, which makes sense because each has a specific function.
The various methods used by classes in ActionScript perform all sorts of tasks, including the following:
We'll demonstrate some of these tasks in this lesson and many others throughout the book.
In this section, we'll briefly review many of the built-in classes that ActionScript provides, as well as some ways they are used. Before we do, however, it's important to discuss how to actually get instances of classes into your project in the first place, so you can begin to utilize their power and functionality.
You can create class instances in one of two ways. To create a new instance of the MovieClip, Button, or TextField class, you create it on the stage or drag it onto the stage from the library. However, only MovieClip, Button, and TextField instances can be created in this way. To create an instance of any other class, you must use a constructora simple line of code that tells Flash to create an instance of a particular class. A constructor looks like this:
var nameOfInstance:nameOfClass = new nameOfClass();
If you want to create an instance of the Sound class, the constructor will look like this:
var mySound:Sound = new Sound();
Whenever you create a class instance, you must give it a unique name. This allows you to change a property or invoke a method as it relates to that particular instance (remember, an instance gets all the properties and methods of the class to which it belongs). We'll demonstrate the concept in examples. As you gain programming experience, you'll begin to understand when you should use constructors.
Although instances of the MovieClip, TextField, and Button classes can be created on the stage manually by dragging them from the library, they can also be created dynamically using ActionScript.
Object names follow the same naming conventions as variables, which means they can't contain spaces, symbols, or a number as the first character.
Some classes are known as top-level classes, and you can't create instances of them using the methods we've shown. What differentiates these classes from those of which you create instances? Top-level classes represent and control global functionalities within your project. Take, for example, the Mouse class, which controls cursor visibility (among other things). You have just one cursor, so it wouldn't make sense to be able to create instances of this class; instead, you use the methods available to it to do various things with the mouse. Look at this example:
This line of script hides the cursor. Notice that the name of an instance is not referenced in relation to the hide() method. Instead, the name of the top-level class is referenced (in this case, Mouse), followed by the name of the method you wish to use. Similar syntax is used with any top-level class. As we go through the rest of this lesson, we'll introduce you to other top-level classes and the syntax required to use them.
In the Actions panel under the ActionScript 2.0 Classes book, you can access all of Flash's built-in classes, each of which is contained in one of the 12 subbooks. These four are the most commonly used:
The following describes many of the built-in classes available in ActionScript as well as where and how you might use them. We'll indicate whether a class is a top-level class (creating instances is not required) or not, in which case you must create individual instances.
Accessibility Class (Top-Level)
This class contains read-only information about the computer's capability to use a screen reader:
This script returns a result of either TRue or false. If the result is true, the user's computer can employ a screen reader.
Array Class (Instances)
An array is a storage device for multiple pieces of information. Arrays store information that can be set and referenced using a numbering system. For example:
var cakeType:Array = new Array(); cakeType = "Chocolate"; cakeType = "Angel Food"; cakeType = "Baked Alaska";
The first line creates a new instance of the Array class called cakeType using the Array constructor. The next lines place data inside that array.
The Array class contains many useful methods that will help you add, remove, and sort array items from instances of that class.
For more on arrays, see Lesson 4, "Arrays and Loops."
Boolean Class (Instances)
Instances of the Boolean class store one of two values: true or false. You can create a Boolean class instance by using the Boolean constructor or by using the = assign operator. For example:
var toggle:Boolean = new Boolean(false);
var toggle:Boolean = false;
create identical instances.
Button Class (Instances)
When you place a button on the stage, you create an instance of the Button class. Only MovieClip and TextField class instances are created in a similar fashionthat is, by placing actual instances on the stage. The Button class contains properties and methods that allow you to control the appearance, tab order, functionality, and more of the button instances.
Capabilities Class (Top-Level)
This class contains information about the user's computer, such as screen resolution and whether it can play sounds. The following script places the horizontal resolution of the user's computer into myVariable:
var myVariable:Number = System.capabilities.screenResolutionX;
Being able to access computer information allows you to create movies that tailor themselves to the capabilities of your user's computer. For example, you can determine whether a handheld computer is accessing the movie and, if so, redirect the user to a page designed expressly for handheld devices.
Color Class (Instances)
You use an instance of this class to change a movie clip's color dynamically. When you create a Color class instance, you point it at a particular movie clip. Using the Color class's methods, you can alter your movie clip's color. You create a Color instance using the Color class constructor method:
var myColor:Color = new Color(pathToTimeline);
Later in this lesson you'll complete an exercise using an instance of the Color class.
ContextMenu Class (Instances)
The context menu is the menu seen in the Flash player when you right-click (Ctrl-click on the Macintosh). This class is used in conjunction with instances of the ContextMenuItems class (described shortly) to create customized context menus (with custom commands), which appear when the user right-clicks (or Ctrl-clicks) a visual element in the Flash player window. This class also allows you to enable most of the built-in context menu commands (such as Play, Stop, and Print), even as your movie plays.
This script creates a new ContextMenu instancenamed myCustomMenu:
var myCustomMenu:ContextMenu = new ContextMenu(); myCustomMenu.hideBuiltInItems(); myCustomMenu.builtInItems.print = true; myMovieClip_mc.menu = myCustomMenu; myButton_btn.menu = myCustomMenu; myTextField_txt.menu = myCustomMenu;
The second line of the script uses the hideBuiltInItems() method to hide all the built-in menu commands, and the third line enables the Print command so that it will appear when the menu is opened. The last three lines assign the custom menu to a movie clip, button, and text field instance. Right-clicking (or Ctrl-clicking) any of these instances will cause the custom menu to appear.
ContextMenuItems Class (Instances)
This class is used in conjunction with the ContextMenu class (described previously) to create items that appear in a custom context menu. Your Flash project can be scripted to capture when a user clicks a custom menu item so that you can have a specific action or actions occur. For example, you can create a custom context menu that will allow a user to right-click in your project and choose to mute the volume.
You will see more on the ContextMenu and ContextMenuItems classes in Lesson 18, "Maximum-Strength SWF Files."
Date Class (Instances)
With this class you can access the current time as local time or Greenwich Mean Time (GMT), as well as easily determine the current day, week, month, or year. To create a new instance of the Date class, you use the Date class constructor method. This example demonstrates one use of the Date class:
var now:Date = new Date(); var largeNumber:Number = now.getTime();
The example creates a variable called largeNumber, whose value is the number of milliseconds since midnight January 1, 1970.
Error Class (Instances)
The Error class was introduced in Flash MX 2004 to help with managing errors in your projects. An error is whatever you define an error to be (a number was too large or too small, for example). When an error occurs, a new instance of the Error class is instantiated, which is known as "throwing" an error. With the Error class you can capture errors and write code to handle them so that your application behaves well, rather than acting in an unpredictable way.
Key Class (Top-Level)
You use the Key class to determine the state of the keys on the keyboardfor example, whether the Caps Lock key is toggled on, which key was pressed last, and which key or keys are currently pressed.
LoadVars Class (Instances)
Flash allows you to load data into a movie from an external source. Using the LoadVars class, Flash can load in variables from a specified URL (which can be a standard text file). For example:
var myObj:LoadVars = new LoadVars(); myObj.load("http://www.mysite.com/myFiles/file.txt");
In this example, all the loaded variables become properties of the myObj LoadVars instance.
Math Class (Top-Level)
With the Math class, you can perform many useful calculations and have the result returned. Here's one:
var positiveNumber:Number = Math.abs(-6);
The script uses the absolute value method of the Math class to convert the 6 to a positive number.
Mouse Class (Top-Level)
The Mouse class controls cursor visibility and allows you to set up Listeners to track mouse activity. Here is an example:
The script hides the mouse from view. The mouse is still active, but it is not visible.
MovieClip Class (Instances)
You create instances of this most familiar class, either in the authoring environment (by placing them on the stage) or with ActionScript actions such as createEmptyMovieClip() and duplicateMovieClip()not by using the constructor function. Movie clip instances have many properties and methods that are used frequently in an interactive project. Here's an example:
With this script, a movie clip with an instance name of myClip_mc will be sent to the frame labeled Menu.
MovieClipLoader Class (Instances)
This class provides a way for you to easily load and gain access to information during the load of a SWF or JPG file into a target movie clip or level. With an instance of the MovieClipLoader class, you know the file size of the external asset you are loading as well as how much of it has been loaded. By continually checking to see how much of the asset has been loaded, you can build a progress bar that indicates how far along an asset is in the loading process.
The MovieClipLoader class also provides a way for you to be informed of when the asset has finished loading.
This class will be used in Lesson 13, "External Data Connections."
NetConnection Class (Instances)
The NetConnection class is used together with the NetStream class to play external Flash Video (FLV) files from an HTTP address or a hard drive.
NetStream Class (Instances)
The NetStream class provides methods and properties for controlling the playback of external Flash Video (FLV) files.
You will see more on the NetConnection and NetStream classes in Lesson 13.
Number Class (Top-Level)
You can create a Number class instance by using its constructor method or by assigning a number as the value of a variable. For instance, the following:
var age:Number = new Number(26);
is equivalent to:
var age:Number = 26;
The new Number() constructor method is rarely used, however, because creating a new number without the constructor takes less effort and achieves the same result.
Object Class (Instances)
No, it's not a typo; there is an Object class! You can use this generic classwhich is also known as ActionScript's root class (meaning that it's the highest in the class hierarchy) in various ways. By employing the properties and methods available to it, you can affect and modify other classes (such as those listed in this section). It also comes in handy for creating object instances that hold information about the current user, or instances that track chunks of related data (to name just a couple of uses).
The following is the syntax for creating a generic object:
var names:Object = new Object(); names.cat = "Hayes";
The first line of script creates a new object called names. The second line adds a variable (property) to the object called cat. The variable is considered a property of this object.
In Lesson 6, "Custom Classes," we'll show you how to create your own custom classes of objects (better than generic objects!) as well as how to create properties and methods for your custom class. After you know how to do this, you can create objects and classes that do precisely what you want.
PrintJob Class (Instances)
This class provides a great way to handle printing. With the PrintJob class you can dynamically specify frames from various timelines to print from a single Print dialog box.
This class is used in Lesson 17, "Printing and Context Menus."
Selection Class (Top-Level)
You use the Selection class to retrieve information or set characteristics relating to selected items in your movies, especially text in text fields. When the cursor is in an area of a text field, that field is said to be "in focus." You can employ the Selection class to set the focus to a specific text field, to find out which text field is currently in focus, or even to programmatically select specific chunks of text in a field so that it can be manipulated in some way. Here's an example of one use of the Selection class:
The script sets into focus the input text field with the instance name of firstName.
You'll complete an exercise using this class later in this lesson.
Sound Class (Instances)
You use instances of the Sound class to control soundsfor example, setting volume and adjusting left and right speaker pan settings. To learn more about this class, see Lesson 16, "Media in Flash."
Stage Class (Top-Level)
With the Stage class, you can control and get information about characteristics of the stage, such as alignment. For example:
The script returns the height of the stage in pixels.
String Class (Instances)
You use the String class to manipulate and get information about textual data. You can create a new string by using the String class constructor method or by putting quotes around a value when setting a variable. For example, the following:
var bird:String = new String("Robin");
is the same as this:
var bird:String = "Robin";
You'll use this class to complete an exercise later in this lesson.
StyleSheet Class (Instances)
The StyleSheet class is used to define a set of style rules for text. It can then be applied to a text field, which makes the text in that text field adhere to the style rules (such as font size and color). The StyleSheet class is useful because you can have several text fields use the same style. If you decide to change something about the style, such as the text color, all the text fields that use the style will be affected. In addition, external Cascading Style Sheet (CSS) files can be used, providing a way to achieve a uniform look to text content in your CSS-enhanced web pages and the Flash content embedded in them (because both can make use of a single style sheet definition). This script creates a new StyleSheet instance and then loads an external CSS file into that instance:
var myStyleSheet = new TextField.StyleSheet(); myStlyeSheet.load("externalStyleSheet.css");
System Class (Top-Level)
This class contains information about your user's computer system, such as the operating system, the language being used, and all the properties of the Capabilities class.
One of the System class's properties is a string called serverString, which contains a list of the system capabilities (concatenated into one string). You can send this list to the server so that you can store or use the information it contains. To access the string, use this:
TextField Class (Instances)
Using this class, you can dynamically create a new text field and control most of its characteristicsfor example, setting the format of the text field or the scrolling of text. Instances of this class are created when a text field is placed on the stage while you're authoring your movie, or created dynamically using the createTextField() method. We'll use this class later in this lesson.
TextFormat Class (Instances)
Instances of the TextFormat class are used to change the format/style of text displayed in text fields. After it's created, you apply the instance of the TextFormat class to a text field using the setTextFormat() or setNewTextFormat() methods:
XML Class (Instances)
XML is one of the most popular standards for formatting datait's no surprise when you consider that XML-formatted data lets all kinds of applications transfer information seamlessly. Using Flash, you can create an XML class instance (which is an instance of the XML class) to store an XML-formatted document that can then be sent from or loaded into XML instances. Here's one use of the XML class:
var myXML:XML = new XML(); myXML.load("myFile.xml");
The script creates a new XML instance and loads an XML-formatted file into that instance.
In Lesson 14, "XML and Flash," you will learn more about using the XML class.
XMLSocket Class (Instances)
Flash also allows you to set up a persistent connection with a socket serveran application that runs on a web server. The socket server waits for users to connect to it. Once connected, the socket server can transfer information between all connected users at very fast speeds, which is how most chat systems and multiplayer games are created. An XML socket is so named because it uses the XML format as the standard for transferred information.
You can create an XMLSocket class instance by using the XMLSocket class constructor method. The following is an example of one use of this type of class:
var mySocket:XMLSocket = new XMLSocket(); mySocket.connect("http://www.electro-server.com", 9875);
This script creates a new instance of the XMLSocket class and opens up a connection with a socket server. See Lesson 14, "XML and Flash," for a detailed description of socket servers and the XMLSocket class, as well as an exercise in creating your own chat application.
Covering every built-in class in detail would take a whole book. However, throughout the lessons we'll use many of these classes discussed here in various ways, and provide detailed instructions about how and why we're using them. The following exercises will concentrate on just a few of these classes to give you a general idea of how you can use them.