![]() ![]() ![]() | |
![]() | |
![]() | |
![]() |
Note: If you have never used ActionScript to write object-oriented scripts and don't need to target Flash Player 5, you should not use the information in this section, because writing scripts using ActionScript 1 is deprecated; instead, see Creating Classes with ActionScript 2.0 for information on using ActionScript 2.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, as in the following example, which creates the methods area()
and diameter()
:
function Circle(radius) { this.radius = radius; this.area = Math.PI * radius * radius; this.diameter = function() {return 2 * this.radius;} }
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.)
The following procedure shows how to assign an area()
method to a custom Circle object.
Circle()
, as follows.
function Circle(radius) { this.radius = radius; }
area()
method of the Circle object. The area()
method calculates the area of the circle. You can use a function literal to define the area()
method and assign the area
property to the circle's prototype object, as follows:
Circle.prototype.area = function () { return Math.PI * this.radius * this.radius; };
var myCircle = new Circle(4);
area()
method of the new myCircle
object, as follows:
var myCircleArea = myCircle.area();
ActionScript searches the myCircle
object for the area()
method. Since the object doesn't have an area()
method, its prototype object Circle.prototype
is searched for area()
. ActionScript finds it and calls it.
![]() | |
![]() | |
![]() | |
![]() ![]() ![]() |