An Object Lesson In JavaScript - Add()ing Some More (
Page 5 of 9 )
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".
<script language="JavaScript">
// object constructor
function Sumthing(num1, num2) {
// object properties
this.alpha = num1;
this.beta = num2;
// object methods
this.Add = Add;
}
// object method Add() - add arguments
function Add() {
sum = this.alpha + this.beta;
return sum;
}
</script>
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
function Sumthing(num1, num2) {
...
// object methods
this.Add = Add;
...
}
to the object constructor block.
Wanna see how it
works? Take a look at the code
<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>
Now *that* is cool!