Web DevCenter    
 Published on Web DevCenter (http://www.oreillynet.com/javascript/)
 See this if you're having trouble printing code examples

ActionScript Cookbook

Introduction to OOP in Flash and ActionScript, Part 1

by Joey Lott, author of ActionScript Cookbook

Object-oriented programming, or OOP, often seems to be shrouded in a veil of mystery. It sounds esoteric, perhaps the kind of thing into which you need to be initiated. And for many, it remains that way because the learning curve with so many development platforms is so high. Enter Flash and ActionScript, and the whole picture changes quite significantly.

Unlike trying to create applications using C++, C#, Java, and the like, Flash and ActionScript don't require any sophisticated IDEs, complicated class path configurations, command line compilation, or ritualistic incantations. With Flash, you just install the authoring application, add your code to a key frame or two, and export your movie. That's one of the benefits. But that's just the tip of the proverbial iceberg.

One of the greatest traditional stumbling blocks with learning object-oriented programming is the inherent abstractness. Just what is an object, after all? Again, Flash and ActionScript come to the rescue. In ActionScript one of the most central types of object happens to be something that can be seen, something with which almost every Flash developer is already reasonably familiar -- the movie clip. Finally, here is an object that we can see. So with this in mind, let's begin by first talking about the definition of an object.

Object Schmobject

Related Reading

Actionscript Cookbook
Solutions and Examples for Flash MX Developers
By Joey Lott

Perhaps surprisingly, an object in computer science and an object in the face-to-face world are remarkably similar. In OOP terminology, an object is something with particular, predictable qualities. We can know the qualities of an object based on its type. This, of course, is not unlike objects with which you interact every day.

For example, an orange is an object. All oranges belong to the orange type. And based on that, we know that the orange object will have certain predictable qualities such as roundness, an orange color, sweetness, etc. In OOP terminology the qualities of an object that are descriptive are called properties. The qualities of an object that produce some kind of action are called methods. For example, an orange can grow, fall from the tree, etc. These are actions for an orange object.

As already mentioned, most programming languages don't make it easy to wrap your mind around this whole object concept. But in the ActionScript world we can see several of the many types of objects, including movie-clip objects. This can really help facilitate the learning of OOP concepts, and make it easier to understand. Not only can we see the objects, but we can also see the effects of the properties and methods of movie-clip objects.

OK. Here's the part where you get to follow along if you want. In order to illustrate the effects of a movie clip's properties and methods, let's try a few experiments.

1. Within a new Flash document create a new movie clip symbol named Circle. And using the circle drawing tool, draw a filled circle on the stage within the Circle symbol.

Figure 1
Figure 1. Creating a new movie clip symbol called Circle.

2. Return to the main timeline (Scene 1) and open the library if you have not yet done so.

3. For best practices, make sure to rename the default layer. Let's name it Circle.

4. Drag an instance of the Circle movie-clip symbol onto the stage so it appears on the left side of the stage.

Figure 2
Figure 2. Dragging a Circle movie clip symbol onto the left side of the stage.

5. Assign an instance name of circle_mc to the new object you just created. You can do this by selecting the circle on the stage, opening the Property inspector, and typing the name in the field that says <Instance Name>.

Figure 3
Figure 3. Assigning an instance name of circle_mc to the new object.

6. Test the movie (ctrl+Enter or cmd+Enter, or choose Control --> Test Movie). At this point we just want to verify that the object appears in the exported movie just as it does during authoring time. This is because in a moment we are going to assign new values to some of the properties, and we want to see the contrast. Once you have verified that the circle appears as it does during authoring time, you can close the .swf and return to the authoring environment.

7. Now we're going to add some simple ActionScript code to assign new values to some of the object's properties. But before we do that, let's add a new layer to the main timeline. It is best to add all your ActionScript to its own layer on any given timeline. By convention, let's name the layer Actions.

8. Select the first (and only) key frame on the Actions layer, and open the Actions panel. You can open the Actions panel by pressing F9.

9. If your Actions panel is in Normal mode, change it to Expert mode now. You can do so by selecting Normal mode from the View Mode menu in the Actions panel. Expert mode enables you to type directly into the Script pane.

Figure 4
Figure 4. Changing the Actions panel to Expert mode.

10. Now, if you recall, we've created an object with the name of circle_mc. In the Script pane let's add some code that tells that object to relocate itself to the right side of the stage. We can accomplish this by assigning new values to the object's _x and _y properties. The first thing we do is address the object by typing its name:


Then, we use a dot to indicate that what will follow will be either a property or method of that object:


We then add the name of the property with which we want to work:


And then, just as with a variable, we can use this property in an assignment statement:

circle_mc._x = 450;

You want to add this single line of code to the Script pane.

Figure 5
Figure 5. Adding the assignment statement to the Script pane.

11. Now that we've added the code, let's test the movie. This time you should notice that the movie-clip object appears on the right side of the stage instead of the left. This is because the _x property affects the x coordinate of the object. By assigning it a value of 450, we told Flash to move the object so that its x coordinate would be 450. When you're done testing the movie, close the .swf and return to the authoring environment.

12. For good measure, let's assign a few more values to a few other properties of the movie clip. Add two more lines of code just after the first:

circle_mc._alpha = 30;
circle_mc._xscale = 150;

13. When you test the movie now, you should see that the movie clip is somewhat transparent and has been scaled to 150% in the x direction.

Figure 6
Figure 6. Test of the movie clip.

Here's another experiment in which we'll utilize one of the methods of a movie-clip object.

  1. Create a new Flash document and within it create a new movie-clip symbol named MorphingCircle.
  2. Within the MorphingCircle, use the circle drawing tool to draw a filled circle on Frame 1.
  3. Select Frame 30 and press F7 to create a new blank key frame.
  4. In Frame 30 use the rectangle drawing tool to draw a square in approximately the same location on the stage as you drew the circle on Frame 1.
  5. Add a shape tween between frames 1 and 30. Move the playhead between frames 1 through 30 to make sure the shape tween causes the circle to morph into a square.

    Figure 7
    Figure 7. Morphing a circle into a square.

  6. Return to the main timeline and open the library.
  7. As a best practice, rename the default layer to Circle Morph.
  8. Drag an instance of MorphingCircle onto the stage.
  9. With the instance selected, open the Property inspector and give it a name of circleMorph_mc.
  10. Test the movie. At this point we just want to verify that the movie clip's timeline plays by default. When you have verified this you may close the .swf and return to the authoring environment.
  11. Add a new layer named Actions.
  12. With the first frame of the Circle Morph layer selected, open the Actions panel by pressing F9.
  13. Make sure you are working in Expert mode, and add the following code to the Script pane:
    The stop() method tells the object from which it is called to stop playback of the timeline. Notice that the method call has two parentheses, called the function call operator (or, in this case, perhaps more accurately, the method call operator). This operator tells Flash to look for a method by this name instead of a property.
  14. Test the movie. This time the movie clip's timeline should be paused at the beginning. This is because you have instructed the movie clip to stop the playback.

Notice that in both of the preceding examples the properties and the method that were referenced affected only the object from which they were referenced. This is part of the design of OOP. Each object has its own set of properties and methods, and when they are referenced from that object, they affect only that object. For example, if you have two movie clips -- circle_mc and square_mc -- then setting the _x property of circle_mc affects only circle_mc, not square_mc. Likewise, if you tell square_mc to play its timeline using the play() method, then square_mc's timeline will play, but not circle_mc.

Gettin' Classy

All movie clip instances are individual objects. Each of them shares a common set of properties, but each one has different values for those properties. And while all movie clips are capable of producing certain actions, they are not necessarily producing those same actions at the same time. This is akin to our orange example. Though oranges share common characteristics, they are all going to be different sizes with variations in color, flavor, etc. Likewise, not all oranges are growing at the same time. Nor are all oranges falling from the tree at the same time.

So how does an object like a movie clip know that it should have a certain set of properties and methods? If you look in the Actions toolbox or the Reference panel within Flash, you see that there are many different types of built-in objects, from the movie clip (MovieClip) and button (Button) types to the XML and Array types. Further examination will reveal that each type has its own properties and methods.

For example, movie clips have properties such as _alpha, _x, _y, and _visible (although these properties show up under the main Properties folder, and not within the MovieClip/Properties folder), while an XML object has properties like nodeType and xmlDecl.

Note: When we talk about built-in classes in Flash/ActionScript, this means that Macromedia has defined these classes, and they are available by default within the Flash authoring application and player.

The answer to our question as to how an object knows what set of properties and methods it should have is that all objects are associated with a prototype. In object-oriented terminology we call this prototype a class. Each of the types listed in the Actions toolbox is a built-in class. MovieClip is a class from which all movie-clip objects are derived. Even though each instance is an individualized object, each movie clip originated from the MovieClip prototype. Therefore, whatever is defined for the prototype (the class) is automatically inherited by each of its instances. So all movie clips have the same set of properties and methods. Likewise, all arrays are derived from the Array class, all XML objects are derived from the XML class, etc.

Constructing Objects

So far, so good? This OOP thing is easier than you thought, right? Now that we've had a chance to examine how to work with movie-clip objects, let's also take a look at some of the other types of objects you can create in ActionScript.

In order to create a movie-clip object you dragged a movie-clip symbol from the library onto the stage and gave it a name. That was simple enough. But how about other types of objects? You cannot create an array symbol or an XML symbol and drag it onto the stage. So how do you go about creating these other types of objects?

Actually, movie clips, buttons, and text fields (all types of objects) are unique in how they are instantiated. The majority of objects are not represented visually on the stage. Instead, most objects are created programmatically using what are known as constructors. A constructor is a special function that shares its name with the class, and when used in a new statement (new is a keyword, a word with specific meaning in ActionScript) these constructors create a new instance of the class. The most fundamental type of object is derived from the Object class. Here's an example of an Object object (an object derived from the Object class) created using a constructor.

var oMyObject = new Object();

The preceding statement tells Flash to create a new object derived from the Object class. The new object is assigned to a variable, oMyObject, so that we can reference it later on in the code.

All the built-in ActionScript classes are dynamic. That means you can add new, custom properties and methods to an instance in addition to getting and setting the properties and methods that are inherited from the class. In order to assign a new custom property you use dot syntax just as if you were assigning a value to an inherited property. If Flash cannot find the property within the object, it creates a new one.

var oMyObject = new Object();
oMyObject.newProperty = "Yay for dynamic properties!";
trace(oMyObject.newProperty); // Displays: Yay for dynamic properties!

Some constructors take parameters. For example, if you want to create a new instance of the Date class that represents a specific time and date, you need to pass it parameters indicating the year, month, day, hour, minutes, seconds, and milliseconds.

var dThen = new Date(2003, 6, 29, 12, 51, 33, 24);
trace(dThen.getFullYear()); // Displays: 2003


We've now taken an introductory look at basic object-oriented principles in ActionScript. I hope this article has helped clarify a few points for you. Obviously, this article only begins to touch on the depth of OOP. In the next installment of this article we'll discuss creating your own custom classes in ActionScript. Between now and then you may also want to consult my ActionScript Cookbook and/or ActionScript for Flash MX: The Definitive Guide for reference material on the built-in ActionScript classes. Additionally, you may find the following links to be useful references:

Joey Lott is a founding partner of The Morphic Group. He has written many books on Flex and Flash-related technologies, including Programming Flex 3, ActionScript 3 Cookbook, Adobe AIR in Action, and Advanced ActionScript 3 with Design Patterns.

O'Reilly & Associates recently released ActionScript Cookbook.

Return to the Web DevCenter.

Copyright © 2009 O'Reilly Media, Inc.