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.
Just as you can define object properties, it's also possible to define object methods - essentially, simple JavaScript functions. A little more evolution, and the Sumthing object now sports an Add() method, which adds the values stored in "alpha" and "beta".
A couple of interesting things here. First, the object
method Add() is actually defined outside the object constructor block, though it references object properties using the "this" keyword. And second, just as object properties are defined using "this", object methods need to be defined in the same manner - witness my addition of
<script language="JavaScript">
obj = new Sumthing(2, 89);
alert("The sum of " + obj.alpha + " and " + obj.beta + " is " + obj.Add());
</script>
and the output.
And
now that your object constructor is all ready to go, let's see a quick demonstration of how you can use it to spawn multiple instances of the same object, each operating independently of the other.
<script language="JavaScript">
// one object
obj1 = new Sumthing(2, 89);
alert("The sum of " + obj1.alpha + " and " + obj1.beta + " is " +
obj1.Add());
// another one
obj2 = new Sumthing(546, 67);
alert("The sum of " + obj2.alpha + " and " + obj2.beta + " is " +
obj2.Add());
// and a third one
obj3 = new Sumthing(2364237, 283457);
alert("The sum of " + obj3.alpha + " and " + obj3.beta + " is " +
obj3.Add());
</script>