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 line


Circle=new Object();


The template is just a function. Inside the function we assign values to this.propertyName. The "this" stuff refers the instance of the object at hand. As we create instances of the object, we values get assigned.

The next thing we do is - to define the properties of the object. Take a look at the table again that defines three properties of the circle - the xcoordinates, ycoordinates and the radius.

Circle=new Object();
Circle.xcoordinate=10;
Circle.ycoordinate=15;
Circle.radius=20;


The example above prints the radius of the circle by assessing its radius property. This is one way of creating the object. What happens if we need to create several instances of circle ? In the next page we will see how to create an object template from which instances of circle can be created. We will then move on to learn methods.

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.