Creating Custom Objects: MethodsTo create a custom method, you just add it to an object as you would a property. Suppose, for example, that you wanted to add a method named display that displayed the person's name in an alert box to a friend object; you could do that like this: function friend(name, phone, rank) { this.name = name this.phone = phone this.rank = rank this.display = display } In the display method, you can refer to the current object with the this keyword; so here's how you can display an object's name in an alert box: function display() { window.alert("Name: " + this.name) } To put this new method to work, I'll add a text field to the example that enables the user to enter a friend's rank to look up, and when the user clicks a button, we can use this function to get the friend with that rank, and use the display method to display the person's name: function getName() { for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){ if(array1[loopIndex].rank == document.form1.text1.value) { array1[loopIndex].display() } } } Here's what that looks like in code: (Listing 23-08.html on the web site)<HTML> <HEAD> <TITLE> Creating Custom Objects </TITLE> </HEAD> <BODY> <H1>Creating Custom Objects</H1> <FORM NAME="form1"> <TEXTAREA NAME="textarea1" ROWS="5" COLS="40"></TEXTAREA> <BR> Friend Rank: <INPUT TYPE="TEXT" NAME="text1"> <INPUT TYPE="BUTTON" ONCLICK="getName()" VALUE="Get Name"> </FORM> <SCRIPT LANGUAGE="JavaScript"> <!-- function friend(name, phone, rank) { this.name = name this.phone = phone this.rank = rank this.display = display } function display() { window.alert("Name: " + this.name) } var array1 = new Array(4) array1[0] = new friend("Ed", "555-1111", 4) array1[1] = new friend("Harold", "555-2222", 1) array1[2] = new friend("Nancy", "555-3333", 3) array1[3] = new friend("Sandy", "555-4444", 2) for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){ document.form1.textarea1.value += "Name: " + array1[loopIndex].name + " " document.form1.textarea1.value += "Phone: " + array1[loopIndex].phone + " " document.form1.textarea1.value += "Rank: " + array1[loopIndex].rank + "\ n" } function getName() { for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){ if(array1[loopIndex].rank == document.form1.text1.value) { array1[loopIndex].display() } } } // --> </SCRIPT> </BODY> </HTML> You can see the results in Figure 23.9, where I've entered a rank of 1, and the code displays the name of the corresponding friend: Harold. Figure 23.9. Creating custom object methods.
|