Assigning methods to a custom object in ActionScript 1.0 795
Assigning methods to a custom object in
ActionScript 1.0
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.0” on page 798.)
The following procedure shows how to assign an
getArea() method to a custom
Circle object.
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.