Understanding ActionScript > About scripting in ActionScript > About object-oriented scripting
About object-oriented scriptingIn object-oriented scripting, you organize information by arranging it into groups called classes. You can create multiple instances of a class, called objects, to use in your scripts. You can use ActionScript's predefined classes and create your own.
When you create a class, you define all the properties (characteristics) and methods (behaviors) of each object it creates, just as real-world objects are defined. For example, a person has properties such as gender, height, and hair color and methods such as talk, walk, and throw. In this example, "person" is a class and each individual person is an object, or an instance of that class.
Objects in ActionScript can contain data or they can be graphically represented on the Stage as movie clips. All movie clips are instances of the predefined class MovieClip. Each movie clip instance contains all the properties (for example, _height
, _rotation
, _totalframes
) and all the methods (for example, gotoAndPlay
, loadMovie
, startDrag
) of the MovieClip class.
To define a class, you create a special function called a constructor function; predefined classes have constructor functions that are already defined. For example, if you want information about a bicycle rider in your movie, you could create a constructor function, Biker
, with the properties time
and distance
and the method
rate
, which tells you how fast the biker is traveling:
function Biker(t, d) { this.time = t; this.distance = d; } function Speed() { return this.time / this.distance; } Biker.prototype.rate = Speed;
You could then create copiesthat is, instancesof the class. The following code creates instances of the object Biker
called emma
and hamish
.
emma = new Biker(30, 5); hamish = new Biker(40, 5);
Instances can also communicate with each other. For the Biker
object, you could create a method called shove
that lets one biker shove another biker. (The instance emma
could call its shove
method if hamish
got too close.) To pass information to a method, you use parameters (arguments): for example, the shove
method could take the parameters who
and howFar
. In this example emma
shoves hamish
10 pixels:
emma.shove(hamish, 10);
In object-oriented scripting, classes can receive properties and methods from each other according to a specific order; this is called inheritance. You can use inheritance to extend or redefine the properties and methods of a class. A class that inherits from another class is called a subclass. A class that passes properties and methods to another class is called a superclass. A class can be both a subclass and a superclass.