Think JavaScript is only good for image swaps and flying <div>s?Think again - this article takes an in-depth look at some of theobject-oriented constructs available in JavaScript, and demonstrates howJavaScript objects can substantially speed up code development anddeployment.
There are a couple of other interesting things about JavaScript objects. For example, should you ever need to, you can obtain complete information on an object's constructor via the "constructor" property. The following example demonstrates how it can be used with the Sumthing object constructor.
<script language="JavaScript">
alpha = new Sumthing(23, 865);
alert("The object constructor for alpha is " + alpha.constructor);
</script>
Here's what it looks like:
And you can use the "prototype" keyword to add new object properties to an already existing object - consider the following addition to the Room object you just saw:
<script language="JavaScript">
// Room object
// accepts area (sq. ft.) and colour (walls) as parameters
function Room(area, colour)
{
this.area = area;
this.colour = colour;
}
Room.prototype.direction = "east";
</script>
This would add an object property named "direction", with
value "east" to the Room object constructor. And when you try to access the object property
<script language="JavaScript">
Kitchen = new Room(1000, "green");
alert(Kitchen.direction);
</script>
you should see this:
The
"prototype" keyword can be used to add object methods as well - try it yourself and see!