Form Validation with JavaScript - Hammer Time
(Page 5 of 10 )
Next, how about modifying the Band() object to accept some arguments.
<script language="JavaScript">
// object constructor
function Band (n, g)
{
// object properties
this.name = n;
this.genre = g;
}
</script>
The object Band now has two properties, "name" and "genre." With this, it is possible to create an instance of the object Band, and pass it two parameters ("n" and "g"), which are then stored as object properties. Note my use of the "this" keyword, which provides a convenient way to access variables (and functions) which are "local" to the object.
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 Band object now sports a whoRules() method, which uses the value stored in the object property "name."
<script language="JavaScript">
// object constructor
function Band(n, g)
{
// object properties
this.name = n;
this.genre = g;
// object methods
this.whoRules = whoRules;
}
// object method whoRules()
function whoRules()
{
alert (this.name + " rules!");
}
</script>
A couple of interesting things here: first, the object method whoRules() is actually defined outside the object constructor block, though it references object properties using the "this" keyword. Second, just as object properties are defined using "this," object methods need to be defined in the same manner. Witness my addition of…
function Band(n, g)
{
...
// object methods
this.whoRules = whoRules;
...
}
… to the object constructor block.Wanna see how it works? Take a look at the code...
<script language="JavaScript">
obj = new Band("SledgeHammer", "Classic Rock");
obj.whoRules();
</script>
... and the output.
SledgeHammer rules!
Next: How Things Work >>
More JavaScript Articles
More By Nariman K, (c) Melonfire