翻译:《JavaScript 权威指南(第5版)》第一章(二)
声明:翻译只有一个目的:学习用途。若有版权问题请及时联系本人。
本贴文根据篇幅将第一章的翻译分为两个部分,这是第二部分的内容。
Figure 1-3 shows what the program looks like when displayed in a web browser. As you can see, it consists of an HTML form and some other text. But the figure captures only a static snapshot of the program. The addition of JavaScript code makes it dynamic: whenever the user changes the amount of the loan, the interest rate, or the number of payments, the JavaScript code recomputes the monthly payment, the total of all payments, and the total interest paid over the lifetime of the loan.
图 1-3 是程序在 web 浏览器中的显示。可以看到,其中是 HTML 表单和一些文本。图虽是静态的截屏图,但 JavaScript 的加入使它动态了:用户更改了借贷数额、利息率、或付款数,JavaScript 代码会重新计算每月的花销、借贷总额、总的利息率,借贷到死为止。
Figure 1-3. A JavaScript loan payment calculator
图 1-3 JavaScript借贷花销计算器
The first half of Example 1-3 is a simple CSS stylesheet and an HTML form, formatted within an HTML table. Note that the form elements define onchange or onclick event handlers. The web browser triggers these event handlers when the user changes the input or clicks on the Compute button displayed in the form, respectively. In each case, the value of the event handler attribute is a string of JavaScript code: calculate(). When the event handler is triggered, it executes this code, which calls the function calculate().
例 1-3 有一半是 CSS 样式表和 HTML 表单,布局为 HTML 表格。在表单元素中定义了 onchange 或 onclick 事件处理。Web 浏览器在用户更改输入或点击计算按钮时会触发这些事件处理并分别在表单中显示。事件处理属性值都为 JavaScript 代码: calculate()。被称之为 calculate() 的函数将会在事件处理触发时执行。
The calculate() function is defined in the second half of the example, inside a <script> tag. The function reads the user's input from the form, does the math required to compute the loan payments, and inserts the results of these calculations into the document within <span> tags that are specially named with id attributes.
示例的下半部分是 calculate() 函数的定义。它位于 <script> 标签内。函数把用户在表单内所输入的内容读取出后,进行了借贷花销的数学计算,然后将这些计算的结果插到文档内的带特定命名的 id 属性的 <span> 标签里。
Example 1-3 is not a short example, but it is straightforward, and it is worth taking the time to look at it carefully. You shouldn't expect to understand all the code at this point, but the HTML, CSS, and JavaScript are all commented, and studying this example will give you the feel for client-side JavaScript.[*]
例 1-3 示例虽然不短,但是不复杂,而且认真看完后会觉得值得一读。在这我们不要求读者对所有代码都理解,但在该例中 HTML、 CSS 、JavaScript 都写有注释,这对读者学习客户端 JavaScript 会有帮助。(注1)
[*] If your intuition tells you that it is a bad idea to intermingle HTML markup, CSS styles, and JavaScript code like this, you are not alone. The trend in JavaScript programming and web design circles is to keep content, presentation, and behavior in separate files. Section 13.1.5 in Chapter 13 explains how to do this.
注1:HTML 标记、CSS 样式、JavaScript 代码混合在一起是不是觉得不好?是的。现在 JavaScript 编程界及 web 设计界已是将内容、表示、行为分离在各自的文件中。详见第13章中 13.1.5 章节。
Example 1-3. Computing loan payments with JavaScript
例 1-3 带 JavaScript 的借贷花销计算
<html> <head> <title>JavaScript Loan Calculator</title> <style> /* This is a CSS style sheet: it adds style to the program output */ .result { font-weight: bold; } /* For elements with class="result" */ #payment { text-decoration: underline; } /* For element with id="payment" */ </style> </head> <body> <!-- This is an HTML form that allows the user to enter data and allows JavaScript to display the results it computes back to the user. The form elements are embedded in a table to improve their appearance. The form itself is given the name "loandata", and the fields within the form are given names such as "interest" and "years". These field names are used in the JavaScript code that follows the form. Note that some of the form elements define "onchange" or "onclick" event handlers. These specify strings of JavaScript code to be executed when the user enters data or clicks on a button. --> <form name="loandata"> <table> <tr><td><b>Enter Loan Information:</b></td></tr> <tr> <td>1) Amount of the loan (any currency):</td> <td><input type="text" name="principal" onchange="calculate();"></td> </tr> <tr> <td>2) Annual percentage rate of interest:</td> <td><input type="text" name="interest" onchange="calculate();"></td> </tr> <tr> <td>3) Repayment period in years:</td> <td><input type="text" name="years" onchange="calculate();"></td> </tr> <tr><td></td> <td><input type="button" value="Compute" onclick="calculate();"></td> </tr> <tr><td><b>Payment Information:</b></td></tr> <tr> <td>4) Your monthly payment:</td> <td>$<span class="result" id="payment"></span></td> </tr> <tr> <td>5) Your total payment:</td> <td>$<span class="result" id="total"></span></td> </tr> <tr> <td>6) Your total interest payments:</td> <td>$<span class="result" id="totalinterest"></span></td> </tr> </table> </form> <script language="JavaScript"> /* * This is the JavaScript function that makes the example work. Note that * this script defines the calculate() function called by the event * handlers in the form. The function reads values from the form * <input> fields using the names defined in the previous HTML code. It outputs * its results into the named <span> elements. */ function calculate() { // Get the user's input from the form. Assume it is all valid. // Convert interest from a percentage to a decimal, and convert from // an annual rate to a monthly rate. Convert payment period in years // to the number of monthly payments. var principal = document.loandata.principal.value; var interest = document.loandata.interest.value / 100 / 12; var payments = document.loandata.years.value * 12; // Now compute the monthly payment figure, using esoteric math. var x = Math.pow(1 + interest, payments); var monthly = (principal*x*interest)/(x-1); // Get named <span> elements from the form. var payment = document.getElementById("payment"); var total = document.getElementById("total"); var totalinterest = document.getElementById("totalinterest"); // Check that the result is a finite number. If so, display the // results by setting the HTML content of each <span> element. if (isFinite(monthly)) { payment.innerHTML = monthly.toFixed(2); total.innerHTML = (monthly * payments).toFixed(2); totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2); } // Otherwise, the user's input was probably invalid, so display nothing. else { payment.innerHTML = ""; total.innerHTML = "" totalinterest.innerHTML = ""; } } </script> </body> </html>
1.4. JavaScript in Other Contexts
1.4. 其他环境中的 JavaScript
JavaScript is a general-purpose programming language, and its use is not restricted to web browsers. JavaScript was designed to be embedded within, and provide scripting capabilities for, any application. From the earliest days, in fact, Netscape's web servers included a JavaScript interpreter so that server-side scripts could be written in JavaScript. Similarly, Microsoft uses its JScript interpreter in its IIS web server and in its Windows Scripting Host product in addition to using it in Internet Explorer. Adobe uses a language derived from JavaScript for scripting its Flash player. And Sun bundles a JavaScript interpreter with its Java 6.0 distribution so that scripting capabilities can easily be added to any Java application (Chapter 12 shows how to do this).
JavaScript是门通用的编程语言。JavaScript 不只是运用于 web 浏览器中,设计时嵌入到任何应用程序就有了脚本编程的能力。回想最初时,因 Netscape 的 web 服务器实际包含了 JavaScript 解释器,所以可用 JavaScript 编写服务器端脚本。而 Microsoft 在其 IIS web 服务器及在其 Windows Scripting Host 用其 JScript 解释器在 IE 中应用。Adobe 用了由 JavaScript 衍生而来的脚本语言应用于 Flash player。Sun 将 JavaScript 解释器与 Java 6.0 捆绑分布,所以给 Java 应用程序加脚本编程比较容易(请见第 12 章)。
Both Netscape and Microsoft have made their JavaScript interpreters available to companies and programmers who want to embed them in their applications. Netscape's interpreter was released as open source and is now available through the Mozilla organization (see http://www.mozilla.org/js/). Mozilla actually provides two different versions of the JavaScript 1.5 interpreter. One is written in C and is called SpiderMonkey. The other is written in Java and, in a flattering reference to this book, is called Rhino.
Netscape 和 Microsoft 均拥有人们可用到而程序员们都想要在其应用程序中嵌入的 JavaScript 解释器。Netscape 的解释器由 Mozilla 组织发布了开源并到现在可下载:http://www.mozilla.org/js/。Mozilla 实际是提供了两种不同版本的 JavaScript 1.5 解释器。一种是 C 编写,称为 SpiderMonkey;另一种是 Java 编写,称为 Rhino。
If you are writing scripts for an application that includes an embedded JavaScript interpreter, you'll find the first half of this book, documenting the core language, to be useful. The web-browser-specific chapters, however, will probably not be applicable to your scripts.
如果是在内嵌了 JavaScript 解释器的应用程序中编写的脚本,那么本书前半部内容是实用的语言核心。而在指定 web 浏览器的章节,也许将会不适用于所编写的脚本。
1.5. Exploring JavaScript
1.5. 深入 JavaScript
The way to really learn a new programming language is to write programs with it. As you read through this book, I encourage you to try out JavaScript features as you learn about them. A number of techniques make it easy to experiment with JavaScript.
下面开始学习这门编程语言,并编写程序。在本书阅读时,我提倡读者在学习相关知识时自己去试验 JavaScript 那些特性。许多 JavaScript 技术一试就不难了。
The most obvious way to explore JavaScript is to write simple scripts. One of the nice things about client-side JavaScript is that anyone with a web browser and a simple text editor has a complete development environment; there is no need to buy or download special-purpose software in order to begin writing JavaScript scripts.
深入 JavaScript 最明显的方式是编写个简单的脚本。web 浏览器都以带有客户端 JavaScript 为荣,而简单的文本编辑器就是 JavaScript 脚本的开发环境,不必订购或下载专门的软件才开始编写啦。
For example, you could modify Example 1-1 to display Fibonacci numbers instead of factorials:
举个示例,想要修改例 1-1 阶乘而以斐波纳契数显示
<script> document.write("<h2>Table of Fibonacci Numbers</h2>"); for (i=0, j=1, k=0, fib =0; i<50; i++, fib=j+k, j=k, k=fib){ document.write("Fibonacci (" + i + ") = " + fib); document.write("<br>"); } </script>
This code may be convoluted (and don't worry if you don't yet understand it), but the point is that when you want to experiment with short programs like this, you can simply type them up and try them out in your web browser using a local file: URL. Note that the code uses the document.write() method to display its HTML output so that you can see the results of its computations. This is an important technique for experimenting with JavaScript. As an alternative, you can also use the alert() method to display plain-text output in a dialog box:
这段代码虽然可能暂时还看不明白,但是没什么关系--你只需把上面的代码输入进去后,在 Web 浏览器中打开本地文件: URL 运行看看是什么结果。注意在代码中使用了document.write() 方法来显示 HTML 的输出,这样的话就可以看到计算的结果。这是一种测验 JavaScript的重要手段。另一种是使用 alert() 方法在对话框显示纯文本的输出内容:
alert("Fibonacci (" + i + ") = " + fib);
Note also that for simple JavaScript experiments like this, you can omit the <html>, <head>, and <body> tags in your HTML file.
还要注意的是,像这样的简单的 JavaScript 测验,可以将HTML 文件中的<html>、<head>、<body>标签省略。
For even simpler experiments with JavaScript, you can sometimes use the javascript: URL pseudoprotocol to evaluate a JavaScript expression and return the result. A JavaScript URL consists of the javascript: protocol specifier followed by arbitrary JavaScript code (with statements separated from one another by semicolons). When the browser loads such a URL, it executes the JavaScript code. The value of the last expression in the URL is converted to a string, and this string is displayed by the web browser as its new document. For example, you might type the following JavaScript URLs into the Location field of your web browser to test your understanding of some of JavaScript's operators and statements:
为了更进一步对 JavaScript 进行测验,可以使用 Javascript:URL 伪协议来对JavaScript 表达式求值并返回结果。JavaScript URL 由javascript: 协议说明符后接任意的JavaScript代码(用分号把语句隔开)。浏览器打开这样的 URL 时,它将会执行 JavaScript 代码。在 URL 中最后一个表达式的值会转换为字符串并在 web 浏览器中当作新文档显示出来。比如,在 web 浏览器的地址栏[1]( Location field)中输入下面的 JavaScript URL 来测验 JavaScript 的运算符、语句:
译注1:Location field :IE和google Chrome称为:地址栏。Firefox 称为:位置。
javascript:5%2 javascript:x = 3; (x > 5)? "x is less": "x is greater" javascript:d = new Date(); typeof d; javascript:for(i=0,j=1,k=0,fib=1; i>5; i++,fib=j+k,k=j,j=fib) alert(fib); javascript:s=""; for(i in navigator) s+=i+":"+navigator[i]+"\n"; alert(s);
In the Firefox web browser, you can also type single-line experiments into the JavaScript console, which you access through the Tools menu. Simply type in an expression you want to evaluate or a statement you want to execute. When using the console instead of the location bar, you omit the javascript: prefix.
在 Firefox web 浏览器中也可以在 JavaScript 控制台(点击菜单栏的“工具”可找到它)中敲一行代码来进行测验。在表达式中简单的输入想要求的值或想要执行的语句。用控制台来代替地址栏的话,可省略前缀 javascript:。
While exploring JavaScript, you'll probably write code that doesn't work as you expect it to, and you'll want to debug it. The basic debugging technique for JavaScript is like that in many other languages: insert statements into your code to print out the values of relevant variables so that you can try to figure out what is actually happening. As shown previously, you can use the document.write() or alert() methods to do this. (Example 15-9 provides a more sophisticated facility for logging debugging messages.)
在深入 JavaScript 时,也有可能会编写的结果与你意想不一致的代码,然后会想要进行调试。JavaScript 的调试手段跟其他许多语言一样:在代码中插入输出相关变量的值的语句,试着在脑海中描绘出实际上发生了什么。前面已经讲了,你可以用document.write() 或alert() 方法来做。(例 15-9 提供了一个用于记录调试信息的很复杂的工具)
The for/in loop (described in Chapter 6) is also useful for debugging. You can use it, along with the alert() method, to display a list of the names and values of all properties of an object, for example. This kind of function can be handy when exploring the language or trying to debug code.
For/in 循环也对调试非常有用。比如可以将它与 alert() 方法一起使用,编写出一个显示对象所有属性的名、值列表的函数。这样的函数在深入这门语言或调试代码时都很便利。
If your JavaScript bugs are persistent and aggravating, you may be interested in an actual JavaScript debugger. In Internet Explorer, you can use Microsoft Script Debugger. In Firefox, you can use a debugger extension known as Venkman. Both tools are beyond the scope of this book, but you can find them easily with an Internet search. Another useful tool that is not strictly a debugger is jslint, which looks for common problems in JavaScript code (see http://jslint.com).
如果你的 JavaScript bug 越来越多,你可能会对一款真正的 JavaScript 调试工具感兴趣。在Internet Explorer 中可以使用Microsoft Script Debugger。在 Firefox 中可以使用调试工具扩展(如Venkman)。这两款工具超出本书内容范围,但是你可以在 Internet 中很容易就能搜到。另一个有用的工具不是严格意义上的调试工具 jslint--查找JavaScript 代码的公共问题(详见http://jslint.com)