User:Moncur/06
6. Using Functions and Objects
[wax ka badal]Using Functions
[wax ka badal]The scripts you've seen so far are simple lists of instructions. The browser begins with the first statement after the <script> tag and follows each instruction in order until it reaches the closing </script> tag (or encounters an error).
Although this is a straightforward approach for short scripts, it can be confusing to read a longer script written in this fashion. To make it easier for you to organize your scripts, JavaScript supports functions, which you learned about in [Hour 3], "Getting Started with JavaScript Programming." In this section, you will learn how to define and use functions.
Defining a Function
[wax ka badal]Functions are groups of JavaScript statements that can be treated as a single unit. To use a function, you must first define it. Here is a simple example of a function definition:
function Greet() { alert("Greetings."); }
This defines a function that displays an alert message to the user. This begins with the function keyword. The function's name is Greet. Notice the parentheses after the function's name. As you'll learn next, the space between them is not always empty.
The first and last lines of the function definition include braces ({ and }). You use these to enclose all of the statements in the function. The browser uses the braces to determine where the function begins and ends.
Between the braces, this particular function contains a single line. This uses the built-in alert() function, which displays an alert message. The message will contain the text "Greetings."
- By the Way
- Function names are case sensitive. If you define a function such as Greet() with a capital letter, be sure you use the identical name when you call the function.
Now, about those parentheses. The current Greet() function always does the same thing: Each time you use it, it displays the same message. Although this avoids a bit of typing, it doesn't really provide much of an advantage.
To make your function more flexible, you can add parameters, also known as arguments. These are variables that are received by the function each time it is called. For example, you can add a parameter called who that tells the function the name of the person to greet. Here is the modified Greet() function:
function Greet(who) { alert("Greetings, " + who); }
Of course, to use this function, you should include it in an HTML document. Traditionally, the best place for a function definition is within the <head> section of the document. Because the statements in the <head> section are executed first, this ensures that the function is defined before it is used.
[Listing 6.1] shows the Greet() function embedded in the header section of an HTML document.
- Listing 6.1. The Greet() Function in an HTML Document
<html> <head> <title>Functions</title> <script language="JavaScript" type="text/javascript"> function Greet(who) { alert("Greetings, " + who); } </script> </head> <body> This is the body of the page. </body> </html>
- By the Way
- As usual, you can download the listings for this hour or view them online at this book's website.
Calling the Function
[wax ka badal]You have now defined a function and placed it in an HTML document. However, if you load [Listing 6.1] into a browser, you'll notice that it does absolutely nothing. This is because the function is defined—ready to be used—but we haven't used it yet.
Making use of a function is referred to as calling the function. To call a function, use the function's name as a statement in a script. You will need to include the parentheses and the values for the function's parameters. For example, here's a statement that calls the Greet function:
Greet("Fred");
This tells the JavaScript interpreter to transfer control to the first statement in the Greet function. It also passes the parameter "Fred" to the function. This value will be assigned to the who variable inside the function.
- By the Way
- Functions can have more than one parameter. To define a function with multiple parameters, list a variable name for each parameter, separated by commas. To call the function, specify values for each parameter separated by commas.
[Listing 6.2] shows a complete HTML document that includes the function definition and a second script in the body of the page that actually calls the function. To demonstrate the usefulness of functions, we'll call it twice to greet two different people.
- Listing 6.2. The Complete Function Example
<html> <head> <title>Functions</title> <script language="JavaScript" type="text/javascript"> function Greet(who) { alert("Greetings, " + who); } </script> </head> <body> <h1>Function Example</h1> <p>Prepare to be greeted twice.</p> <script language="JavaScript" type="text/javascript"> Greet("Fred"); Greet("Ethel"); </script> </body> </html>
This listing includes a second set of <script> tags in the body of the page. The second script includes two function calls to the Greet function, each with a different name.
Now that you have a script that actually does something, try loading it into a browser. You should see something like [Figure 6.1], which shows the Greeting script running in Firefox.
- By the Way
- Notice that the second alert message isn't displayed until you press the OK button on the first alert. This is because JavaScript processing is halted while alerts are displayed.
Returning a Value
[wax ka badal]The function you just created displays a message to the user, but functions can also return a value to the script that called them. This allows you to use functions to calculate values. As an example, you can create a function that averages four numbers.
Your function should begin with the function keyword, the function's name, and the parameters it accepts. We will use the variable names a, b, c, and d for the four numbers to average. Here is the first line of the function:
function Average(a,b,c,d) {
- By the Way
- I've also included the opening brace ({) on the first line of the function. This is a common style, but you can also place the brace on the next line, or on a line by itself.
Next, the function needs to calculate the average of the four parameters. You can calculate this by adding them, and then dividing by the number of parameters (in this case, 4). Thus, here is the next line of the function:
result = (a + b + c + d) / 4;
This statement creates a variable called result and calculates the result by adding the four numbers, and then dividing by 4. (The parentheses are necessary to tell JavaScript to perform the addition before the division.)
To send this result back to the script that called the function, you use the return keyword. Here is the last part of the function:
return result; }
[Listing 6.3] shows the complete Average() function in an HTML document. This HTML document also includes a small script in the <body> section that calls the Average() function and displays the result.
- Listing 6.3. The Average() Function in an HTML Document
<html> <head> <title>Function Example</title> <script language="JavaScript" type="text/javascript"> function Average(a,b,c,d) { result = (a + b + c + d) / 4; return result; } </script> </head> <body> <p>The following is the result of the function call.</p> <script LANGUAGE="JavaScript" type="text/javascript"> score = Average(3,4,5,6); document.write("The average is: " + score); </script> </body> </html>
You can use a variable with the function call, as shown in this listing. This statement averages the numbers 3, 4, 5, and 6 and stores the result in a variable called score:
score = Average(3,4,5,6);
- Did you Know?
- You can also use the function call directly in an expression. For example, you could use the alert statement to display the result of the function: alert(Average(1,2,3,4)).
Introducing Objects
[wax ka badal]In the previous hour, you learned how to use variables to represent different kinds of data in JavaScript. JavaScript also supports objects, a more complex kind of variable that can store multiple data items and functions.
Although a variable can have only one value at a time, an object can contain multiple values, as well as functions for working with the values. This allows you to group related data items and the functions that deal with them into a single object.
In this hour, you'll learn how to define and use your own objects. You've already worked with some objects:
- DOM objects Allow your scripts to interact with web pages. You learned about these in [Hour 4], "Working with the Document Object Model (DOM)."
- Built-in objects Include strings and arrays, which you learned about in [Hour 5], "Using Variables, Strings, and Arrays."
The syntax for working with all three types of objects—DOM objects, built-in objects, and custom objects—is the same, so even if you don't end up creating your own objects, you should have a good understanding of JavaScript's object terminology and syntax.
Creating Objects
[wax ka badal]When you created an array in the previous hour, you used the following JavaScript statement:
scores = new Array(4);
The new keyword tells the JavaScript interpreter to use a function—in this case, the built-in Array function—to create an object. You'll create a function for a custom object later in this hour.
Object Properties and Values
[wax ka badal]Each object has one or more properties—essentially, variables that will be stored within the object. For example, in [Hour 4], you learned that the location.href property gives you the URL of the current document. The href property is one of the properties of the location object in the DOM.
You've also used the length property of String objects, as in the following example from the previous hour:
test = "This is a test." document.write(test.length);
Like variables, each object property has a value. To read a property's value, you simply include the object name and property name, separated by a period, in any expression, as in test.length previously. You can change a property's value using the = operator, just like a variable. The following example sends the browser to a new URL by changing the location.href property:
location.href="http://www.jsworkshop.com/";
- By the Way
- An object can also be a property of another object. This is referred to as a child object.
Understanding Methods
[wax ka badal]Along with properties, each object can have one or more methods. These are functions that work with the object's data. For example, the following JavaScript statement reloads the current document, as you learned in [Hour 4]:
location.reload();
When you use reload(), you're using a method of the location object. Like normal functions, methods can accept arguments in parentheses, and can return values.
Using Objects to Simplify Scripting
[wax ka badal]Although JavaScript's variables and arrays are versatile ways to store data, sometimes you need a more complicated structure. For example, suppose you are creating a script to work with a business card database that contains names, addresses, and phone numbers for a variety of people.
If you were using regular variables, you would need several separate variables for each person in the database: a name variable, an address variable, and so on. This would be very confusing.
Arrays would improve things slightly. You could have a names array, an addresses array, and a phone number array. Each person in the database would have an entry in each array. This would be more convenient, but still not perfect.
With objects, you can make the variables that store the database as logical as business cards. Each person is represented by a Card object, which has properties for name, address, and phone number. You can even add methods to the object to display or work with the information.
In the following sections, you'll use JavaScript to actually create the Card object and its properties and methods. Later in this hour, you'll use the Card object in a script to display information for several members of the database.
Defining an Object
[wax ka badal]The first step in creating an object is to name it and its properties. We've already decided to call the object a Card object. Each object will have the following properties:
- name
- address
- workphone
- homephone
The first step in using this object in a JavaScript program is to create a function to make new Card objects. This function is called the constructor for an object. Here is the constructor function for the Card object:
function Card(name,address,work,home) { this.name = name; this.address = address; this.workphone = work; this.homephone = home; }
The constructor is a simple function that accepts parameters to initialize a new object and assigns them to the corresponding properties. This function accepts several parameters from the statement that calls the function, and then assigns them as properties of an object. Because the function is called Card, the object is the Card object.
Notice the this keyword. You'll use it anytime you create an object definition. Use this to refer to the current object—the one that is being created by the function.
Defining an Object Method
[wax ka badal]Next, you will create a method to work with the Card object. Because all Card objects will have the same properties, it might be handy to have a function that prints out the properties in a neat format. Let's call this function PrintCard().
Your PrintCard() function will be used as a method for Card objects, so you don't need to ask for parameters. Instead, you can use the this keyword again to refer to the current object's properties. Here is a function definition for the PrintCard() function:
function PrintCard() { line1 = "Name: "+ this.name + "<br>\n"; line2 = "Address: " + this.address + "<br>\n"; line3 = "Work Phone: " + this.workphone + "<br>\n"; line4 = "Home Phone: " + this.homephone + "<hr>\n"; document.write(line1, line2, line3, line4); }
This function simply reads the properties from the current object (this), prints each one with a caption, and skips to a new line.
You now have a function that prints a card, but it isn't officially a method of the Card object. The last thing you need to do is make PrintCard() part of the function definition for Card objects. Here is the modified function definition:
function Card(name,address,work,home) { this.name = name; this.address = address; this.workphone = work; this.homephone = home; this.PrintCard = PrintCard; }
The added statement looks just like another property definition, but it refers to the PrintCard() function. This will work so long as the PrintCard() function is defined with its own function definition. Methods are essentially properties that define a function rather than a simple value.
- Did you Know?
- The previous example uses lowercase names such as workphone for properties, and an uppercase name (PrintCard) for the method. You can use any case for property and method names, but this is one way to make it clear that PrintCard is a method rather than an ordinary property.
Creating an Object Instance
[wax ka badal]Now let's use the object definition and method you just created. To use an object definition, you create a new object. This is done with the new keyword. This is the same keyword you've already used to create Date and Array objects.
The following statement creates a new Card object called tom:
tom = new Card("Tom Jones", "123 Elm Street", "555-1234", "555-9876");
As you can see, creating an object is easy. All you do is call the Card() function (the object definition) and give it the required attributes, in the same order as the definition.
After this statement executes, a new object is created to hold Tom's information. This is called an instance of the Card object. Just as there can be several string variables in a program, there can be several instances of an object you define.
Rather than specify all the information for a card with the new keyword, you can assign them after the fact. For example, the following script creates an empty Card object called holmes, and then assigns its properties:
holmes = new Card(); holmes.name = "Sherlock Holmes"; holmes.address = "221B Baker Street"; holmes.workphone = "555-2345"; holmes.homephone = "555-3456";
After you've created an instance of the Card object using either of these methods, you can use the PrintCard() method to display its information. For example, this statement displays the properties of the tom card:
tom.PrintCard();
Extending Built-in Objects
[wax ka badal]JavaScript includes a feature that enables you to extend the definitions of built-in objects. For example, if you think the String object doesn't quite fit your needs, you can extend it, adding a new property or method. This might be very useful if you were creating a large script that used many strings.
You can add both properties and methods to an existing object by using the prototype keyword. (A prototype is another name for an object's definition, or constructor function.) The prototype keyword enables you to change the definition of an object outside its constructor function.
As an example, let's add a method to the String object definition. You will create a method called heading, which converts a string into an HTML heading. The following statement defines a string called title:
title = "Fred's Home Page";
This statement would output the contents of the title string as an HTML level 1 heading:
document.write(title.heading(1));
[Listing 6.4] adds a heading method to the String object definition that will display the string as a heading, and then displays three headings using the method.
- Listing 6.4. Adding a Method to the String Object
<html> <head> <title>Test of heading method</title> </head> <body> <script LANGUAGE="JavaScript" type="text/javascript"> function addhead (level) { html = "H" + level; text = this.toString(); start = "<" + html + ">"; stop = "</" + html + ">"; return start + text + stop; } String.prototype.heading = addhead; document.write ("This is a heading 1".heading(1)); document.write ("This is a heading 2".heading(2)); document.write ("This is a heading 3".heading(3)); </script> </body> </html>
First, you define the addhead() function, which will serve as the new string method. It accepts a number to specify the heading level. The start and stop variables are used to store the HTML "begin header" and "end header" tags, such as <h1> and </h1>.
After the function is defined, use the prototype keyword to add it as a method of the String object. You can then use this method on any String object or, in fact, any JavaScript string. This is demonstrated by the last three statements, which display quoted text strings as level 1, 2, and 3 headers.
Try It Yourself Storing Data in Objects
[wax ka badal]Now you've created a new object to store business cards and a method to print them out. As a final demonstration of objects, properties, functions, and methods, you will now use this object in a web page to display data for several cards.
Your script will need to include the function definition for PrintCard(), along with the function definition for the Card object. You will then create three cards and print them out in the body of the document. We will use separate HTML and JavaScript files for this example. [Listing 6.5] shows the complete script.
- Listing 6.5. An Example Script That Uses the Card Object
// define the functions function PrintCard() { line1 = "<b>Name: </b>" + this.name + "<br>\n"; line2 = "<b>Address: </b>" + this.address + "<br>\n"; line3 = "<b>Work Phone: </b>" + this.workphone + "<br>\n"; line4 = "<b>Home Phone: </b>" + this.homephone + "<hr>\n"; document.write(line1, line2, line3, line4); } function Card(name,address,work,home) { this.name = name; this.address = address; this.workphone = work; this.homephone = home; this.PrintCard = PrintCard; } // Create the objects sue = new Card("Sue Suthers", "123 Elm Street", "555-1234", "555-9876"); phred = new Card("Phred Madsen", "233 Oak Lane", "555-2222", "555-4444"); henry = new Card("Henry Tillman", "233 Walnut Circle", "555-1299", "555-1344"); // And print them sue.PrintCard(); phred.PrintCard(); henry.PrintCard();
Notice that the PrintCard() function has been modified slightly to make things look good with the captions in boldface. To use this script, save it as cardtest.js. Next, you'll need to include the script in a simple HTML document. [Listing 6.6] shows the HTML document for this example.
- Listing 6.6.
- The HTML File for the Card Object Example
<html> <head> <title>JavaScript Business Cards</title> </head> <body> <h1>JavaScript Business Card Test</h1> <p>Script begins here.</p><hr> <script language="JavaScript" type="text/javascript" src="cardtest.js"> </script> <p>End of script.</p> </body> </html>
To test the script, save the HTML document in the same directory as the cardtest.js file you created earlier, and then load the HTML document into a browser. The browser's display of this example is shown in [Figure 6.2].
- By the Way
- This example isn't a very sophisticated database because you have to include the data for each person in the script. However, an object like this could be used to store a database record retrieved from a database server with thousands of records.
Summary
[wax ka badal]In this hour, you've looked at two important features of JavaScript. First, you learned how to use functions to group JavaScript statements, and how to call functions and use the values they return.
You also learned about JavaScript's object-oriented features—defining objects with constructor functions, creating object instances, and working with properties, property values, and methods.
In the next hour, you'll look at two more features you'll use in almost every script—conditions to let your scripts evaluate data, and loops to repeat sections of code.
Q&A
[wax ka badal]- Q1
- Many objects in JavaScript, such as DOM objects, include parent and child objects. Can I include child objects in my custom object definitions?
- A1
- Yes. Just create a constructor function for the child object, and then add a property to the parent object that corresponds to it. For example, if you created a Nicknames object to store several nicknames for a person in the card file example, you could add it as a child object in the Card object's constructor: this.nick = new Nicknames();.
- Q2
- Can I create an array of custom objects?
- A2
- Yes. First, create the object definition as usual and define an array with the required number of elements. Then assign a new object to each array element (for example, cardarray[1] = new Card();). You can use a loop, described in the next hour, to assign objects to an entire array at once.
- Q3
- Can I modify all properties of objects?
- A3
- With custom objects, yes—but this varies with built-in objects and DOM objects. For example, you can use the length property to find the length of a string, but it is a read-only property and cannot be modified.
Quiz Questions
[wax ka badal]Test your knowledge of JavaScript by answering the following questions:
1. What JavaScript keyword is used to create an instance of an object?
- object
- new
- instance
2. What is the meaning of the this keyword in JavaScript?
- The current object.
- The current script.
- It has no meaning.
3. What does the prototype keyword allow you to do in a script?
- Change the syntax of JavaScript commands.
- Modify the definitions of built-in objects.
- Modify the user's browser so only your scripts will work.
Quiz Answers
[wax ka badal]1. b. The new keyword creates an object instance.
2. a. The this keyword refers to the current object.
3. b. The prototype keyword allows you to modify the definitions of built-in objects.
Exercises
[wax ka badal]To further explore the JavaScript features you learned about in this hour, you can perform the following exercises:
- Modify the Greet() function to accept two parameters, who1 and who2, and to include both names in a single greeting dialog. Modify [Listing 6.2] to use a single function call to the new function.
- Modify the definition of the Card object to include a property called email for the person's email address. Modify the PrintCard() function in [Listing 6.5] to include this property.