Understanding the ActionScript Language > About custom objects > Assigning methods to a custom object

 

Assigning methods to a custom object

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.)

The following procedure shows how to assign an area method to a custom Circle object.

 
To assign a method to a custom object:

1

Define the constructor function Circle, as follows:

function Circle(radius) {
	this.radius = radius;
}

2

Define the 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;
};

3

Create an instance of the Circle object, as follows:

var myCircle = new Circle(4);

4

Call the 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 the area method. ActionScript finds it and calls it.