Introduction to ActionScript 2.0/Properties and Methods

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Introduction to ActionScript 2.0
Functions Properties and Methods Control Statements


Key concepts:


  • Properties and methods
  • Global functions and variables
  • The main timeline as a MovieClip
  • Dot access
  • this, this._parent
  • with
  • Property access with []
  • Basic MovieClip methods and properties
  • Initialisation with constructors
  • Object literals
  • null, undefined

Properties and methods are the two components that constitute a class. A property is a variable that belongs to a certain class. A method is a function that belongs to a certain class. This chapter is about this important twosome.

What are top-level functions and global variables?[edit | edit source]

ActionScript provides a huge number of built-in functions. Some of these functions are methods of built-in classes like MovieClip and Math. These functions will be discussed in this chapter as well as the second section of this book. Other built-in functions do not belong to a built-in class. They can be used whenever you want, wherever you want in your file. Our beloved trace() is one of these functions. These functions are called top-level functions or global functions.

A global variable is a variable that can be accessed and changed anywhere you want. The _quality variable is a good example: it affects the quality of the entire SWF. They are provided by Flash.[1]

Breaking news![edit | edit source]

We interrupt this chapter to bring you some breaking news!

Since you made it to this chapter, it's time to break the news to you: The main timeline (the timeline on which you've been working on all along) is a MovieClip instance.

What does this imply?

All objects have properties and methods, remember? Therefore, the main timeline has various built-in properties and methods we have to learn. We will learn some of them in this chapter, and save the rest for the next section.

Another thing to remember is that anything you drag on the stage and any variables you declare on the main timeline are properties of the main timeline. The reason why new properties can be added to the instance is because MovieClip is a dynamic class. We will talk about dynamic classes in the third section.

How can I access the property of another object?[edit | edit source]

The most common way to access the property of another object is as follows:

objectName.propertyName

Note that in order for this to work, we have to ensure that propertytName is a property of what we're working on.

Let's try this out. Open Flash. Create a new MovieClip in the library. Draw an apple in it and drag it anywhere onto the stage. Give it the instance name of 'apple'.[2] Now click on the apple again. on the first frame, type in var juiciness:Number = 5. (Recall: all variables you declare in a timeline is a property of that MovieClip.) Type in the following code:

Code Result
trace(apple.juiciness);

5

In this code, we have traced the juiciness property of the apple using the dot operator.

What are this and _parent?[edit | edit source]

this is used to address the current location. For example, if you're in the Main Timeline, this.crunchiness will return the crunchiness of the main timeline. Let's try out our apple example again with this.

Code Result
trace(this.apple.juiciness);

5

This does the same thing, except it explicitly states that apple is a property of the current object (the main timeline). As you can see, this is not always necessary.

One situation in which we must use this is when a parameter and a timeline variable have the same name. In this case, one must put this before the timeline variable so that the computer knows you're not talking about the local variable. Here's an example:

Code Result
var someString:String = "random text";
function stringTogether(someString:String):String{
     return (someString + " " + this.someString);
}
trace(stringTogether("even randomer text"));

even randomer text random text

In this example, return (someString + " " + this.someString); concatenates the local variable someString, a space character and a timeline variable someString together.

So far, we've only been referencing the apple from the main timeline. Is it possible to reference the main timeline from the apple? The answer: yes, and it involves _parent.

Open the Flash file with the apple again and type in the following code:

Code Result

In the first frame of the main timeline:

var crunchiness:Number = 7;

In the first frame of the apple symbol:

trace(this._parent.crunchiness);

7

In this example, the apple is contained in the main timeline, so the main timeline is the apple's 'parent'. Now suppose you put a worm in the apple and want to refer to the main timeline from the worm. No problem: you can put in as many layers of _parent as necessary:

Code Result

In the first frame of the main timeline:

var crunchiness:Number = 7;

In the first frame of the worm symbol:

trace(this._parent._parent.crunchiness);

7

The worm's parent is the apple and the apple's parent is the main timeline. Works like magic!

What's with with?[edit | edit source]

Now suppose the worm goes on a quest to reduce the crunchiness and sweetness of the main timeline and the juiciness of the apple. We can do this:

Code Result

In the first frame of the main timeline:

var crunchiness:Number = 7;
var sweetness:Number = 4;

In the first frame of the apple symbol:

var juiciness:Number = 6;

In the first frame of the worm symbol:

this._parent._parent.crunchiness--;
this._parent._parent.sweetness--;
this._parent.juiciness--;
trace(this._parent._parent.crunchiness);
trace(this._parent._parent.sweetness);
trace(this._parent.juiciness);

6
3
5

Now suppose we're too lazy to type in 'this._parent' so many times. We can use with to solve this problem:

Code Result

In the first frame of the main timeline:

var crunchiness:Number = 7;
var sweetness:Number = 4;

In the first frame of the apple symbol:

var juiciness:Number = 6;

In the first frame of the worm symbol:

with(this._parent){
     _parent.crunchiness--;
     _parent.sweetness--;
     juiciness--;
}
trace(this._parent._parent.crunchiness);
trace(this._parent._parent.sweetness);
trace(this._parent.juiciness);

6
3
5

That saves us from having to type in this._parent three times. All the computer has to interpret your code is to append this._parent in front of each statement in the block.

What if I want to treat the property name as a string?[edit | edit source]

Sometimes, we need to treat a property name as a string so that we can concatenate several strings to form the property name. Here's an example:

Code Result
var currentAnimal:String = "cat";
var dogFood:String = "biscuits";
var catFood:String = "fish";
var fishFood:String = "smallerFish";
trace(this[currentAnimal + "Food"])

fish

In this example, we concatenated currentAnimal ('cat') and 'food' to form the property name catFood, returning the string 'fish'.[3]

How can I access an object's properties through a variable?[edit | edit source]

In the second chapter, we've learnt that by assigning anything other than a primitive data type to a variable, we are putting a link to that object inside the variable. We can also access an object's properties with a variable:

Code Result

In the first frame of the main timeline:

var someFruit:MovieClip = apple;
trace(apple.juiciness);
trace(apple["juiciness"]);

In the first frame of the apple symbol:

var juiciness:Number = 6;

6
6

What are some MovieClip properties and methods that I must know?[edit | edit source]

The following are some MovieClip properties that will be used throughout the rest of the section.[4]

  • _x and _y (both numbers) indicate the position of a MovieClip relative to its parent. Remember that in ActionScript, the higher the value of _y, the lower the position of the MovieClip. The origin (0,0) is located on the top-left corner. This may be counter-intuitive if you are familiar with Cartesian planes.
  • _width and _height (both numbers) indicate width (horizontal) and height (vertical) dimension of a MovieClip respectively.
  • _visible indicates whether the MovieClip is visible. If _visible is true, the MovieClip is visible and vice versa.
  • _currentframe indicates which frame the MovieClip is currently on.

_x, _y, _width, _height and _visible can all be changed by assigning a different value to them. Open the Flash file with the apple again and type in the following code:

apple._x = 100;
apple._y = 200;
apple._width = 100;
apple._height = 100;

You should find noticeable changes in the position and dimensions of the apple (unless, of course, your apple happened to have exactly the same position and dimensions on the stage!)

Unlike the others, _currentframe cannot be changed with assignment statements. Instead, several functions are used to manipulate the current frame:

  • play() and stop() will play and stop playing the frames in order respectively. The default is to play, so whenever you want to stop at a frame, you should add the stop() code. For example, if you put nothing on the first five frames, then stop() on the sixth, Flash will play until the sixth frame.
  • gotoAndPlay(frame) and gotoAndStop(frame) will go to the specified frame, then play and stop the Flash respectively. If there is a stop() statement on the target frame of gotoAndPlay, Flash will stop, and if there is a play() statement on the target frame of gotoAndStop, Flash will also stop.
  • prevFrame() and nextFrame() go to the previous and next frame respectively. Unless there is a stop() statement on the target frame, they will play.

More properties and methods will be introduced in the second section.

How can I call a method of another object?[edit | edit source]

Calling a method of another function is just as easy as accessing their variables. Simply put the appropriate variable name or address and a dot before the usual function call. Let's say we have a second frame on our apple MovieClip with a half-eaten apple.

Code Result

In the first frame of the main timeline:

apple.nextFrame();

In the first frame of the apple symbol (a complete apple complete with a worm):

stop();
trace("First frame!");

In the second frame of the apple symbol (a half-eaten apple):

stop();
trace("Second frame!");

First frame!
Second frame!

In this example, the worm symbol traces 'First frame!' when it is initialised, but the main timeline will quickly make the apple symbol go to the second frame.

What is a constructor?[edit | edit source]

A constructor function is the most important method of a class. It is used to initialise an instance of a class. Remember the syntax for initialisation that we learnt in the first chapter? Although it worked perfectly for the primitive data types, it is more complicated for the composite data types (which you can't type in directly).

We won't learnt how to make our own constructor functions until the third chapter. For now, let's stick to calling constructor functions. The syntax for calling a constructor function is as follows:[5]

var variableName:DataType = new DataType(parameter1, parameter2);

For instance, let's say there's a Dog class and we want to make a new Dog instance. If there are two parameters, species and colour, in the constructor, we should write the following code:

Code Result
//Assume there is a Dog class.
var spot:Dog = new Dog("chihuahua", "black");
trace(Dog.species);
trace(Dog.colour);

chihuahua
black

This creates a new spot instance of the Dog class with the species 'chihuahua' and the colour 'black'.

The primitive data types can also be applied the constructor function when they are initialised. This will be covered in the second section.

It is possible to use a constructor class outside of variable declaration/assignment statements. This will create an instance without a warm and cozy variable home.

Code Result
trace(new Number());

0

When don't I need a constructor?[edit | edit source]

Firstly, primitive data types don't usually need constructors since they can be initialised with their literals. For example, var someString:String = "Wikibooks" will do, and you don't have to write someString:String = new String("Wikibooks").[6]

We don't need to use the constructor function on the Object class, either. (Remember the Object class? It is the grand-daddy of all classes.) Instead, it can be generated like this:[7]

var variableName:Object = {property1:value1, property2:value2, ..., method1:function1, method2:function2 ...};

The function1, function2, etc., should be replaced with the syntax for putting a function inside a variable (which we've met in the functions chapter). Look at this example:

Code Result
var someObject:Object = {
     crunchiness:7,
     juiciness:5,
     eat:function(){
          trace("Mmmm! It's " + this.crunchiness + " on the crunchiness scale and "
           + this.juiciness + " on the juiciness scale.");
     }
     };
trace(someObject.crunchiness);
someObject.eat();

7
Mmmm! It's 7 on the crunchiness scale and 5 on the juiciness scale.

A new object is created with 7 as its crunchiness and 5 as its juiciness.

What are null and undefined?[edit | edit source]

In computer science if a value is null or undefined, there isn't anything in it. For example, the key field in a database table must be unique and non-null, which means it can't be empty. In ActionScript, null and undefined are two flexible, all-purpose values that can be put into variables of any type. A variable which is not yet defined (i.e. you haven't assigned any value to it and haven't called its constructor) is automatically set to undefined. Null and undefined are considered equivalent values with the normal equality operator (i.e. null == undefined returns true), but not the strict equality operator (i.e. null === undefined returns false). Consider the following example:

Code Result
var someNumber:Number;
trace(someNumber);
someNumber = null;
trace(someNumber);
var someString:String = undefined;
trace(undefined == null);
trace(undefined === null);

undefined
true
true
false

In this example, someNumber is at first undefined, then set to null. Next, someString is set to undefined. (That is just to show that undefined can be fit into any data type.) Finally, it is found that undefined is equal, but not strictly equal, to null.

One should be more careful when using the ! operator with null and undefined.

Code Result
var someBoolean:Boolean;
trace(!someBoolean);
var someNumber:Number;
trace(!someNumber);

true
true

In the first trace, someBoolean was undefined. !someBoolean means 'someBoolean is not true', which is different from saying 'someBoolean is false'. Since someBoolean was undefined, it was 'not true' (but not false either), so !someBoolean is true. Also note that a number can be used with the ! operator when it's undefined, as shown in the second trace statement.

Notes[edit | edit source]

  1. It is also possible to define your own global variables like this: _global.variableName = value; Notice that global variables are not strong typed. Defining your own global variables is a deprecated practice and should be used sparingly.
  2. You can change the instance name of any MovieClip in the Properties panel.
  3. In fact, there is more to this syntax than meets the eye, but let's keep up the suspense until the third section.
  4. In ActionScript 3.0, all the leading underscores have been abolished.
  5. Instances of the MovieClip and TextField classes are created with special methods. We'll discuss them in the second section.
  6. There is a subtle difference between these two. "Wikibooks" is just a primitive string literal, while new String("Wikibooks") is an object of the String wrapper class. We will learn more about this in the second section.
  7. Note that the parts enclosed in braces are also considered a literal of the object.