796 Object-Oriented Programming with ActionScript 1.0
To assign a method to a custom object:
1. Define the constructor function Circle():
function Circle(radius) {
this.radius = radius;
}
2.
Define the getArea() method of the Circle object. The getArea() method calculates the
area of the circle. In the following example, you can use a function literal to define the
getArea() method and assign the getArea property to the circle’s prototype object:
Circle.prototype.getArea = function () {
return Math.PI * this.radius * this.radius;
};
3.
The following example creates an instance of the Circle object:
var myCircle = new Circle(4);
4.
Call the getArea() method of the new myCircle object using the following code:
var myCircleArea = myCircle.getArea();
trace(myCircleArea); // traces 50.265...
ActionScript searches the myCircle object for the getArea() method. Because the object
doesn’t have a
getArea() method, its prototype object Circle.prototype is searched for
getArea(). ActionScript finds it, calls it, and traces myCircleArea.
Defining event handler methods in
ActionScript 1.0
You can create an ActionScript class for movie clips and define the event handler methods in
the prototype object of that new class. Defining the methods in the prototype object makes all
the instances of this symbol respond the same way to these events.
You can also add an
onClipEvent() or on() event handler methods to an individual instance
to provide unique instructions that run only when that instance’s event occurs. The
onClipEvent() and on() methods don’t override the event handler method; both events
cause their scripts to run. However, if you define the event handler methods in the prototype
object and also define an event handler method for a specific instance, the instance definition
overrides the prototype definition.
NOTE
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 7,
“Classes,” on page 225.