Học JavaScript qua ví dụ part 19 pps

9 481 0
Học JavaScript qua ví dụ part 19 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 166 Chapter 7 • Functions 7.1.6 Functions Are Objects For a discussion on how functions behave as objects. See “Classes and User-Defined Functions” on page 182 in Chapter 8, “Objects.” 7.2 Debugging Techniques Now that we have covered some of the fundamental JavaScript constructs, this is a good time to introduce some debugging techniques. As your programs grow, so do your chances to create errors. Getting to know how to deal with these problems will save you much time and frustration. 7.2.1 Function Syntax When working with functions there are some simple syntax rules to watch for: 1. Did you use parentheses after the function name? 2. Did you use opening and closing curly braces to hold the function definition? 3. Did you define the function before you called it? Try using the typeof operator to see if a function has been defined. 4. Did you give the function a unique name? 5. When you called the function is your argument list separated by commas? If you don’t have an argument list, did you forget to include the parentheses? 6. Do the number of arguments equal to the number of parameters? 7. Is the function supposed to return a value? Did you remember to provide a vari- able or a place in the expression to hold the returned value? 8. Did you define and call the function from within a JavaScript program? Figure 7.17 shows function errors displayed by the JavaScript Error Console in Firefox. This is a very useful debugging tool for immediate error checking. Just click the Tools menu and go to Error Console. These error messages make troubleshooting your scripts much easier. Figures 7.18 through 7.20 show errors in other browsers. Figure 7.17 Function errors in the JavaScript Error Console (Firefox). From the Library of WoweBook.Com ptg 7.2 Debugging Techniques 167 Figure 7.18 Windows Internet Explorer—Look in the bottom left corner of the page. Double-click the yellow icon. A window will appear with the line and character where the error was found. Figure 7.19 Windows Internet Explorer Debug tool. From the Library of WoweBook.Com ptg 168 Chapter 7 • Functions 7.2.2 Exception Handling with try/catch and throw An exception is a runtime error that the program might encounter during its execution, such as an undefined variable, an index value that is referenced but doesn’t exist, a func- tion that receives a bad parameter, and so on. Exception handlers make it possible to catch errors and resolve them gracefully. By catching the exception and controlling the error message, the program will be much nicer for an unwary user who is not used to the kinds of error messages you see all the time. As of JavaScript1.5 exception handling is now supported. The try/catch Statements. You can enclose and test those parts of a program where you expect potential problems in a try statement. If an exception occurs within the try block, control will shift to the catch block. The catch block will contain statements to clarify what went wrong. If there were no errors, the catch block will be ignored. See Examples 7.12 and 7.13. When an exception is thrown in the try block, the variable shown as e in catch(e) holds the value of the type of exception (Table 7.1) that was thrown in the try block. You can use this variable to get information about the exception that was thrown. (The variable e can have any name and is local to the catch block.) You can use the name and message properties with the catch variable to get the name of the exception and a message explaining what caused the exception. Figure 7.20 Opera’s Error Console. From the Library of WoweBook.Com ptg 7.2 Debugging Techniques 169 Table 7.1 Primary Error Types (JavaScript 1.5+) Error Name When It Is Raised EvalError If the eval() function is used in an incorrect manner RangeError If a numeric variable or parameter exceeds its allowed range ReferenceError If an invalid reference is used; e.g., the variable is undefined SyntaxError If a syntax error occurs while parsing code in an eval() TypeError If the type of a variable or parameter is a valid type URIError Raised when encodeURI() or decodeURI() are passed invalid parameters EXAMPLE 7.12 <html> <head><title>Try/Catch</title> <script type="text/javascript"> 1 try { alert("Current balance is $:" + get_balance()); } 2 catch(err) { alert("Something went wrong! \n"+ 3 err.name +":"+ err.message); } </script> </head> </html> EXPLANATION 1 The try block contains the JavaScript that will be tested for errors. 2 If an error occurred in the try block, it would be caught in the catch block. 3 The argument, err, contains the reason for the error. Without the try/catch state- ments, this example would display a blank page and the error would show up in the browser’s error console. If the exception is caught in your program, it will not show up in the browser’s console window (see Figure 7.21). From the Library of WoweBook.Com ptg 170 Chapter 7 • Functions The throw Statement. The throw statement allows you to create your own condi- tions for exceptions. Used within in the try block, a specific error condition can be tested and thrown to the catch block. In the catch block you can create customized error mes- sages to correspond to a particular error. See Example 7.13. The finally Clause. You can use the finally clause to execute statements after the try statement finishes, whether or not an exception occurred. You can use the finally clause to make your script fail gracefully when an exception occurs; for example, you might need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally clause closes the file before the script fails. Figure 7.21 An error was caught and its name and the reason for it are displayed. EXAMPLE 7.13 <html> <head><title>Catch me if you Can!</title></head> <body> <script type="text/javascript"> 1 var age=eval(prompt("Enter your age:","")); 2 try{ 3 if(age>120 || age < 0){ throw "Error1"; } else if(age == ""){ 4 throw "Error2"; } else if(isNaN(age)){ throw "Error3"; } } 5 catch(err){ 6 if(err=="Error1"){ alert("Error! The value is out of range"); } From the Library of WoweBook.Com ptg 7.2 Debugging Techniques 171 if(err=="Error2"){ alert("Error! You didn't enter your age"); } if(err=="Error3"){ alert("Error! The value is not a number"); } } 7 if (age < 13){ alert("You pay child's fare!"); } else if(age < 55 ){ alert("You pay adult fare."); } else { alert("You pay senior fare."); } </script> </body> </html> EXPLANATION 1 This simple example is here to show you how the try/catch/throw statements can be used for handling errors. For something like this, you will probably find it eas- ier to test the program in the if conditionals, but we’ll use it to demonstrate how to throw exceptions. First, the user is prompted for his or her age. 2 The try block is entered to test for the possible error conditions defined by the programmer. 3 If an invalid age is entered (i.e., an age less than 0 or greater than 120). An error string, “Error1” is thrown and picked up in the catch block to be tested. 4 If the user didn’t enter anything, the string “Error2” is thrown and picked up in the catch block. 5 In the catch block, the errors will be handled based on the error string that was thrown from the try block. 6 The err value being passed to the catch block is one of the values that was thrown from the try block; for example, “Error1”, “Error2”, “Error3”. 7 Because all the testing and error handling was handled in the try/catch blocks, the rest of the program can continue with no further testing of the age variable (see Figure 7.22). EXAMPLE 7.13 (CONTINUED) From the Library of WoweBook.Com ptg 172 Chapter 7 • Functions 7.3 What You Should Know Functions are fundamental to programming in any programming language. There are JavaScript built-in functions such as eval(), parseInt(), and Number(), among others, and there are user-defined functions. This chapter was all about defining and calling your own functions. We will be creating functions throughout the rest of this text to perform tasks based on user-initiated events such as clicking a link, clicking a button, rolling a mouse over an image, or submitting a form. Functions will be defined within JavaScript code or from another file. They may be used to create objects, respond to HTTP requests, validate data, perform calculations, customize output, and so on. After reading this chapter, you should know: 1. How to declare and define functions. 2. Where to put functions in a JavaScript program. 3. How to call a function with arguments and use parameters. 4. What can be returned from a function. 5. The difference between global and local variables. 6. How to trigger a function call. 7. How to assign a function to a variable. 8. What closure is. 9. What recursion is. 10. How try and catch work. 11. How to debug programs with browser tools. Figure 7.22 Example of output for Example 7.13. From the Library of WoweBook.Com ptg 7.3 What You Should Know 173 1. Copy the following file and execute it in your browser. What’s wrong with it and why? Can you fix it? <html> <head><title>link</title> <script type="text/javascript"> function addem(){ var n = 2; var y = 3; document.write( n + y , "<br />"); } </script> </head> <body bgcolor="red"> <a href="JavaScript:addem()">Click here</a> <h2>Hello</h2> </body> </html> 2. Write a function that will calculate and return the amount that should be paid as a tip for a restaurant bill. The tip will be 20 percent of the total bill. 3. Create a function called changeColor() that will be called when the user presses one of two buttons. The first button will contain the text “Press here for a yellow background”. The second button will contain the text “Press here for a light green background”. The function will take one parameter, a color. Its function is to change the background color of the current document; for example, bgColor=“yellow”. 4. Write a function called isLeapYear() that will return true if this is a leap year and false if it isn’t. 5. Write an anonymous function that will calculate and return the distance you have traveled using the formula, rate * time. The function definition will be assigned to a variable. The function will be called using the variable. 6. The following example is written in the C language. It is a very common recur- sive function call factorial. Can you explain how this function works and can you write it in JavaScript? unsigned int factorial(unsigned int n){ if (n <= 1) { return 1; } else { Exercises Exercises From the Library of WoweBook.Com ptg 174 Chapter 7 • Functions return n * factorial(n-1); } } 7. Write a function that returns the total cost of any number of buckets of paint. Ask the user how many buckets he or she is going to buy and for the cost of one bucket. Ask the user the color of the paint. Calculate and return what he or she owes. Change the color of the font to the color of the paint. Use the catch/try/throw statements to check for invalid input if the user doesn’t give you a valid value for the number of buckets, such as a number less than 0, or gives you no input, or types in a string, and so on, check that the user doesn’t give you a color of paint that is the same color as the background of your document or you will not be able to see the color of the font. From the Library of WoweBook.Com . value? 8. Did you define and call the function from within a JavaScript program? Figure 7.17 shows function errors displayed by the JavaScript Error Console in Firefox. This is a very useful. error messages you see all the time. As of JavaScript1 .5 exception handling is now supported. The try/catch Statements. You can enclose and test those parts of a program where you expect potential. Chapter 8, “Objects.” 7.2 Debugging Techniques Now that we have covered some of the fundamental JavaScript constructs, this is a good time to introduce some debugging techniques. As your programs

Ngày đăng: 04/07/2014, 02:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan