4. December 2009 14:11
Creating an Object in JavaScript
The whole point of object oriented programming is to work with objects you can define yourself. You can create an object for virtually anything. It can hold information on a customer, the dimensions of a rectangle, or even the specifications of your car. To use your object you must create a template, that will hold all of the qualities of you object. To use your template, you must create a new instance of your object to apply values to it. The keyword 'this' is used as a reference to the current object.
<script type="text/javascript">
function rectangle(length,width)
{
this.length=length;
this.width=width;
this.area=this.length*this.width;
}
function newRect()
{
var rect=new rectangle(9,3);// calls a new rectangle object, giving it the shown values
return rect.area;// returns the area of the new rectangle
}
</script>
<input onclick="alert(newRect())" type="button" value="New Rectangle" />
In this example we created an object to hold a the length and width of a rectangle. Then we created another function to create new rectangle objects.
14cef77b-05d0-4429-958a-4f8b5f12a006|2|2.0