Javascript TUTORIAL


Javascript Objects - Mehod


In the last page we looked at how define the template of a circle and create instances of it. Now we will define a method on the object circle. The method will calculate the area of the circle. Let us take a look at the example

Example - A circle object with a method to calculate area


<html>
<head>
<script type="text/javascript">
<!--
/*
************************************************************
Example Circle Object - method to calculate area
************************************************************
*/

function circle(x,y,r)
{
this.xcoordinate=x;
this.ycoordinate=y;
this.radius=r;
this.area = calculatearea;
}
function calculatearea() {
return ( 3.14 * this.radius * this.radius );
}
/*
********************************************************
Let us create an instances of object circle
********************************************************
*/
circle1 =new circle(0,0,10);
document.write("The radius of the 1st circle is " + circle1.radius + " <p>");
/*
********************************************************
Let us call the area method
********************************************************
*/
document.write( 'The area of the circle is ' + circle1.area() );
//-->
</script>
</head>
<body>
</html>



Note the line

this.area = calculatearea;


defines a method on the object cicle. The calculatearea , in turn is a function that we have defined subsequently.


You can try the example at the link below which will open in a new window

Example - Object Mehods

Let us take a look at another example which moves the origin of the circle by calling another method move origin.

<html>
<head>
<script type="text/javascript">
<!--
/*
************************************************************
Example Circle Object - method to calculate area
************************************************************
*/

function circle(x,y,r)
{
this.xcoordinate=x;
this.ycoordinate=y;
this.radius=r;
this.moveorigin = move;
}
function move(dx,dy) {
this.xcoordinate = this.xcoordinate +dx; this.ycoordinate = this.ycoordinate +dy;
}
circle1 =new circle(0,0,10);
document.write("The original coordinates are " + circle1.xcoordinate +" ," + circle1.ycoordinate +" <p>");
/*
********************************************************
Let us call the move method
********************************************************
*/
circle1.moveorigin(5,7);
document.write("The new coordinates are " + circle1.xcoordinate +" ," + circle1.ycoordinate +" <p>");
//-->
</script>
</head>
<body>
</html>



You can try the example at the link below which will open in a new window

Example - Circle move origin

This completes the basic javascript tutorial. You may like to practice more and take up some advanced topics in javascript tutorial.