Javascript TUTORIAL


Javascript Objects - Introduction


An object in Javascript comprises of two things

1. A collection of properties (variables) and 2. Methods (functions) - all classed under a single name.

Let us imagine that there is an object named circle. The object circle possesses three properties: the x coordinate of its center, the y coordinate of its center and its radius.The circle possesses some methods: CalculateArea , CalculateCircumference, MoveOrigin.

In JavaScript the obejects come under two broad categories - First you may create your own objects for storing data and define and use the methods on it. Secondly, there are many "built-in" objects which allow you to work with, manipulate, and access the Web page and Web browser. These are known as the "Document Object Model".


Properties


Let us take a look at the following example that defines an object circle and three of its properties - xcoordinates, ycoordinates , radius. It just prints out the radius of the circle

Example - A circle object with properties


<html>
<head>
<script type="text/javascript">
<!--
/*
********************************************************
Example Circle Object
********************************************************
*/
Circle=new Object();
Circle.xcoordinate=10;
Circle.ycoordinate=15;
Circle.radius=20;
document.write("The radius of the circle is " + Circle.radius );
//-->
</script>
</head>
<body>
</html>


You may try the above example online at the link below ( opens in a new window )

Javascript Circle Object Example

Note the line

Circle=new Object();


This defines a new Object that has the name Circle.

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.