Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Object-Oriented Programming with ActionScript 1.0 > Assigning methods to a custom object in ActionScript 1.0 | |||
|
NOTE |
Many Flash users can greatly benefit from using ActionScript 2.0, especially with complex applications. For information on using ActionScript 2.0, see Classes. |
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.)
The following procedure shows how to assign an getArea() method to a custom Circle object.
To assign a method to a custom object:Circle():
function Circle(radius) {
this.radius = radius;
}
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;
};
var myCircle = new Circle(4);
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.
|
|
|
|