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.
Nothing too fancy here - the constructor simply creates
an object, initializes it with a temperature and temperature scale, and runs a conversion function to obtain the equivalent temperature in the other scale. A raiseTemp() method is included to demonstrate how object properties can be altered.
It should be noted here that it is also possible to directly adjust the object properties without using the raiseTemp() method. I say "technically", because it is generally not advisable to do this, as it would violate the integrity of the object; the preferred method is always to use the methods exposed by the object to change object properties. By limiting yourself to exposed methods, you are provided with a level of protection which ensures that changes in the object constructor code do not have repercussions on your code.
And here's how you could use the object in an HTML document.
<script language="JavaScript">
// create an object instance
a = new Thermometer(98.6, "f");
// access object properties
alert("Temperature in Fahrenheit is " + a.degreesF);
alert("Temperature in Celsius is " + a.degreesC);
// execute object methods
a.raiseTemp(10);
alert("Temperature in Fahrenheit is " + a.degreesF);
alert("Temperature in Celsius is " + a.degreesC);
</script>