Login | Register
Flash ActionScript - Objects

Flash ActionScript - Objects

In the real world there are objects like i.e. an apple. An apple has properties like smell, color, size and position. We use objects in special ways that we can refer to as methods. In Flash, movie clips and buttons are objects.

Flash Objects can have properties, methods or both. Flash has many native (built-in) objects that you can take advantage of for handling everything from arrays to XML files. This article focuses on building your own objects with Flash and requires a basic to intermediate understanding of the Actionscript programming language.

Object Basics
If you're familiar with object-oriented programming languages, such as C++, you're used to having to define object methods and properties in a class structure before using them in an instance. ActionScript can be, but doesn't have to be so formal.

Object Creation
It's very easy to create an object in ActionScript, using the generic built-in object called Object.

person1 = new Object();



Adding Properties
Compared to languages like C++, you don't have to declare a property in a class structure. You can just add it at runtime like this:

person1.firstName = "Frodo";



Accessing Properties
You can access properties in an object either through the dot syntax or by using array access.

trace( person1.firstName );
trace( person1[ "firstName" ] );



Adding Methods
In ActionScript, you can assign a function to a variable name, and call it indirectly by using the variable.

function myFunc( msg ) { trace( msg ); }
 iFunc = myFunc;  // assign function to variable
 iFunc( "Hello world!" );  // make indirect call



The principal also works for objects and their associated methods. To add a method to an object, you can assign it just like you assigned a property.

person1.sayName = function() {
 trace( this.firstName );
 }
 person1.sayName(); // call the function



What's This?
You may have noticed in the last example that I referred to the firstName parameter as this.firstName. When writing methods, it is a good idea to use the special keyword this to make sure that you're referring to the property and methods used in the current object.

Object Destruction
Although ActionScript handles garbage collection (meaning that you don't have to explicitly delete objects when your program terminates), you can explicitly delete objects yourself, using the delete keyword.

delete person1; // delete the object.



Instead of deleting the whole object, you could just delete parts of it:

delete person1.firstName; // delete the property.



Object Referencing
You can create multiple references to a single object by assigning an object to a second variable. Both variables will be referring to the same object.

person1 = { first: "Frodo", last: "Baggins" };
 person2 = person1; // Create another reference
 person1.first = "Bilbo";
 trace( person2.first ); // will return "Bilbo"



If you delete either object, internally ActionScript just deletes a reference counter. The object remains available to the remaining variable.

person1 = { first: "Frodo", last: "Baggins" };
 person2 = person1; // Create a 2nd reference
 person1.first = "Bilbo";
 delete person1; // internally decreases counter
 trace( person2.first ); // will return "Bilbo"



When the internal reference count for an object drops to zero, Flash internally will mark the object for garbage collection. You don't have to worry about it.

Object Scope
Objects follow the same rules as other variables in regard to scope. By using the var keyword, you can ensure that an object is local.

var person1 = new Object(); // scope restricted



Child Objects
You can create objects within objects (known as child objects).

person1.address = new Object();
person1.address.street = "123 Main Street";



Object Initialization
You can declare an empty object, or reset an existing object by using an empty pair of curly brackets.

person1 = {};
person1 = new Object();



Name / Value Pairs
You can also initialize an object by filling the curly brackets with a set of name / value pairs. Name / value pairs use the format name : value and are separated by commas.

person1 = 
{ firstName: "Frodo", lastName: "Baggins" };
trace( person1.firstName );



This is a very useful feature that you should become familiar with. Name / value pairs can also be used to initialize movie clips and components.

// attach a movie clip and set it's _x and _y parameters
attachMovie( "FClip", "mc1", 101, { _x: 10, _y: 20 } );



Using With
You can save a lot of typing and make your code much more readable by using with to share the reference to an object.

person1.address.street = "123 Main Street";
person1.address.city = "Boston";
person1.address.state = "MA";
person1.address.zip = "02114";
 
with( person1.address ) {  // more readable
 street = "123 Main Street";
 city = "Boston";
 state = "MA";
 zip = "02114"; }



Using Undefined
When working with objects, it is sometimes useful to test whether or not they have been instantiated. You can test for instantiation by using the keyword undefined.

if( myObject == undefined )
 { myObject = { name: "Frodo" }; }



Iteration
You can loop over the name/value pairs of an object using for ... in.

for( name in myObject )
 { trace( name + ":" + myObject[ name ]; }



Exercise 01: New Object
In this exercise, you will create a new object and add some properties and methods to it.

Create the function
1. Enter the following into the Actions panel for Frame 1:

// Define the object.
person1 = new Object();
// Add some properties.
person1.first = "Frodo";
person1.last = "Baggins";
// Add a method.
person1.sayHello = function() {
trace( "Hello, my name is " + this.first );
}
// Examine the object.
trace( person1.first );
trace( person1.last );
// Call method.
person1.sayHello();



Test your movie
2. Select from the main menu: Control / Test Movie
3. The results should appear in the Output window

Exercise 02: New Object Initializer
In this exercise, you will use name / value pairs to initialize the properties of an object.

Create the function
1. Enter the following into the Actions panel for Frame 1:

// Initialize an object with properties.
person1 = { first: "Frodo", last: "Baggins" };
person1.sayHello = function() { // Add a method.
trace( "Hello, my name is " + this.first );
}
trace( person1.first ); // Examine the object.
trace( person1.last );
person1.sayHello(); // Call the method.



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Exercise 03: Delete
In this exercise, you will learn how to delete an object and a property.

Create the function
1. Enter the following into the Actions panel for Frame 1:

// Initialize an object with properties.
person1 = { first: "Frodo", last: "Baggins" };
// Create another reference to the object.
person2 = person1;
delete person1; // Delete the initial reference.
trace( person1.first ); // undefined 
trace( person2.first ); // "Frodo"
delete person2.first;   // Delete a property. 
trace( person2.first ); // undefined
trace( person2.last );  // "Baggins"



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Exercise 04: Dot Operator
In this exercise, you will use dot syntax to access multiple levels of properties in an object.

Create the function
1. Enter the following into the Actions panel for Frame 1:

// Initialize an object.
building = { type: "Theater" };
// Add an object as a property.
building.floor = { level: 1 };
trace( building.type ); // Reference the parent.
trace( building.floor.level ); // Ref the child.



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Exercise 05: Undefined
In this exercise, you will use the undefined keyword to test for the existence of an object. If the object does not exist, it will be created.

Create the function
1. Enter the following into the Actions panel for Frame 1:

function test() {
    if( myObject == undefined ) {
    trace( "Creating new object." );
    myObject = { name: "Frodo" };
  } else {
    trace( "Object is already defined." );
  }
  trace( myObject.name );
}
test(); // Create the object.
test(); // The object is already defined.



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Exercise 06: With
In this exercise, you will use the with keyword to simplify references to the properties of an object.

Create the function
1. Enter the following into the Actions panel for Frame 1:

person1 = { first: "Frodo", last: "Baggins" };
 
with( person1 ) {
  trace( first ); // person1.first
  trace( last ); // person1.last
}



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Exercise 07: Object Array Access
In this exercise, you will use array access to access properties within an object.

Create the function
1. Enter the following into the Actions panel for Frame 1:

person1 = { first: "Frodo", last: "Baggins" };
trace( person1[ "first" ] ); // "Frodo"



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Exercise 08: Iteration
In this exercise, you will use for ... in to dump the contents of an object.

Create the function
1. Enter the following into the Actions panel for Frame 1:

 

function dump( obj ) {
for( name in obj ) {
   // loop through the object properties.
// reference each property by name.
trace( name + ": " + obj[ name ] );
trace( typeof( obj[ name ] ) );
}
}
person1 = { first: "Frodo", last: "Baggins", age: 23 };
dump( person1 );



Test your movie
2. Select from the main menu: Control / Test Movie
3. The result should appear in the Output window

Review
In this article, you learned about:
- Creating new objects
- Initializing objects
- Deleting objects and properties
- Using the dot operator to access object methods and properties
- Using the Undefined keyword
- Using the With keyword to simplify your code
- Access object properties as an array
- How to loop through an objects properties

This article has been adapted from the book Flash MX ActionScript: for Programmers by Mitch Allen (mitch@mitchallen.com) and Priscilla Grogan (editor) (priscilla@sqaoutsource.com) ISBN: 0-9725676-0-7. For more information, please visit http://www.gahitsuPress.com or http://www.mitchallen.com.

 

Get new stories first

Click to follow us on Twitter!

 

Comments


Posted by Gus on 12/25 at 05:35 PM

To wet my feet with Flash, I’m trying to revamp an older flash file (v. 6, I believe).  There are five images in the library.  The first remains as a backdrop throughout the movie and the other four take turns appearing in front of the background.  With each successive change of those four images there is a different text message, so four in total, defined in the action script.  I’ve been knocking myself out to simply get rid of one of the images—and of course one of the messages.  If I delete one message and one image, I’m faced with a red panel in lieu of the image when the movie plays.  Is there an easier way to simply remove one entire element in the array without a lot of fuss?


Posted by Jens C Brynildsen on 12/30 at 09:16 PM

Hi Gus,
First of all - this sounds like something that is done easier using the timeline. If you want to do it with Actionscript instead, I’d read up on Arrays in the official Adobe documentation or look at the Array tutorials on this page:

http://www.flashmagazine.com/Tutorials/category/actionscript_basics/

Briefly said - you’ll need to copy the content of the array up until the element you want to remove and then append what comes after it. Maybe using two Slice-commands:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html#slice()

J


Posted by jhocking on 07/12 at 05:37 PM

I want to add one thing to the “Iteration” information listed here. If you don’t care about the names and only want the values then you can use a “for each” loop, like so:

for each (value in obj) {

This was a very helpful explanation for figuring out how to use Object so I wanted to add that tidbit.

Submit a comment

Only registered members can comment. Click here to login or here to register