Categories:

How to add methods to your own object

Adding methods to a user defined object is a bit more complicated. We need to first declare and define a function for each method, then associate this function with the object function. For the sake of simplicity, we will simply call functions defined for methods "method functions." Lets get a clean start, and create a new object called "circle" that will contain methods that compute the area and diameter of a circle, respectively.

The first step to adding methods is to implement the method functions. Method functions define what a method does:

//first method function
function computearea(){
	var area=this.radius*this.radius*3.14
	return area
}

//second method function
function computediameter(){
	var diameter=this.radius*2
	return diameter
}

In the above case, we've created two method functions, "computearea" and "computediamter", which calculates various aspects of a circle. The two functions, as you can see, are just functions, with one major distinction. Take the first one, for example:

function computearea(){
	var area=this.radius*this.radius*3.14
	return area
}

What the heck is this.radius? It looks like a property of a custom object to me (back up and see how a property is defined in a custom object). Since a method function will eventually be connected to the custom object, it has access to the properties of the object. We haven't defined the properties yet, but we will, and the method functions will use them in its calculation.

We will now associate the two method functions above to the new object "circle", so they become methods of the object:

<script type="text/javascript">
//the below creates a new object, and gives it the two methods defined earlier
function circle(r){
	this.radius=r //property that stores the radius 
	this.area=computearea
	this.diameter=computediameter
}
</script>

Finally, to use these methods, instantiate the object, and access the methods just like any other method:

<script type="text/javascript">
var mycircle=new circle(20)
alert("area="+mycircle.area()) //alerts 1256
alert("diameter="+mycircle.diameter()) //alerts 400
</script>

As you can see, creating your own objects requires quite a bit of work, but can be very rewarding and even necessary as your JavaScript becomes more sophisticated.