User Guide

About ActionScript 1 325
Creating a custom object in ActionScript 1
To create a custom object, you define a constructor function. A constructor function is always
given the same name as the type of object it creates. You can use the keyword
this inside the
body of the constructor function to refer to the object that the constructor creates; when you call
a constructor function, Flash passes
this to the function as a hidden parameter. For example, the
following code is a constructor function that creates a circle with the property
radius:
function Circle(radius) {
this.radius = radius;
}
After you define the constructor function, you must create an instance of the object. Use the new
operator before the name of the constructor function, and assign a variable name to the new
instance. For example, the following code uses the
new operator to create a Circle object with a
radius of 5 and assigns it to the variable
myCircle:
myCircle = new Circle(5);
Note: An object has the same scope as the variable to which it is assigned.
Assigning methods to a custom object in ActionScript 1
You can define the methods of an object inside the object’s constructor function. However, this
technique is not recommended because it defines the method every time you use the constructor
function. The following example creates the methods
getArea() and getDiameter(): and
traces the area and diameter of the constructed instance
myCircle with a radius set to 55:
function Circle(radius) {
this.radius = radius;
this.getArea = function(){
return Math.PI*this.radius*this.radius;
};
this.getDiameter = function() {
return 2*this.radius;
};
}
var myCircle = new Circle(55);
trace(myCircle.getArea());
trace(myCircle.getDiameter());
Each constructor function has a prototype property that is created automatically when you
define the function. The
prototype property indicates the default property values for objects
created with that function. Each new instance of an object has a
__proto__ property that refers
to the
prototype property of the constructor function that created it. Therefore, if you assign
methods to an object’s
prototype property, they are available to any newly created instance of
that object. It’s best to assign a method to the
prototype property of the constructor function
because it exists in one place and is referenced by new instances of the object (or class). You can
use the
prototype and __proto__ properties to extend objects so that you can reuse code in an
object-oriented manner. (For more information, see “Creating inheritance in ActionScript 1”
on page 328.)
The following procedure shows how to assign an
getArea() method to a custom Circle object.