Javascript TUTORIAL


Javascript Objects - Object Template


In the last page we looked at how to define a single Circle Object. In practice we would like to define a template for the cicle object. We should be able to create the instances of the circle as many times as possible.

The example below defines a template of the circle object and creates three instances of it.

Example - A circle object with properties


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example Circle Object Template and instances
********************************************************
*/
/*
********************************************************
Let us define the structure of the object circle.
********************************************************
*/
function circle(x,y,r)
{
this.xcoordinate=x;
this.ycoordinate=y;
this.radius=r;
}
/*
********************************************************
Let us create 3 instances of object circle
********************************************************
*/
circle1 =new circle(0,0,10);
circle2 =new circle(5,5,20);
circle3 =new circle(10,10,30);

document.write("The radius of the 1st circle is " + circle1.radius + " <p>");
document.write("The radius of the 2nd circle is " + circle2.radius + " <p>" );
document.write("The radius of the 3rd circle is " + circle3.radius + " <p>" );
//-->
</script>
</head>
<body>
</html>



Note the template to create an instance of an object


Circle=new Object();




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

Example - Circle Object Template

In the next page we will create methods on the object circle. We will see how to create area and circumference of the circle by writing methods.