Creating an Object in JavaScript

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.





Comments

4/23/2010 3:58:24 PM #

disc player

It seems that you are maintaining a steady blogging pace. Well done! Looking for more updates from your end. Thanks a lot!

disc player United States |

5/24/2010 11:26:35 AM #

Casey

You have some honest ideas here. I done a research on the issue and discovered most peoples will agree with your blog.

Casey Puerto Rico |

Comments are closed


About the author

 The creators of the Web Design Blog have been creating web designs for over 12 years

Page List