翻譯:《JavaScript 權威指南(第5版)》第一章(二)

來源:互聯網
上載者:User
文章目錄
  • 1.4. JavaScript in Other Contexts
  • 1.4. 其他環境中的 JavaScript
  • 1.5. Exploring JavaScript
  • 1.5. 深入 JavaScript

聲明:翻譯只有一個目的:學慣用途。若有著作權問題請及時聯絡本人。

本貼文根據篇幅將第一章的翻譯分為兩個部分,這是第二部分的內容。

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 是程式在 網頁瀏覽器中的顯示。可以看到,其中是 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 事件處理。網頁瀏覽器在使用者更改輸入或點擊計算按鈕時會觸發這些事件處理並分別在表單中顯示。事件處理屬性值都為 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 allowsJavaScript to display the results it computes back to the user. Theform elements are embedded in a table to improve their appearance.The form itself is given the name "loandata", and the fields withinthe form are given names such as "interest" and "years". Thesefield 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 beexecuted 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 Contexts1.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 不只是運用於 網頁瀏覽器中,設計時嵌入到任何應用程式就有了指令碼編程的能力。回想最初時,因 Netscape 的 網頁伺服器實際包含了 JavaScript 解譯器,所以可用 JavaScript 編寫伺服器端指令碼。而 Microsoft 在其 IIS 網頁伺服器及在其 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 解譯器的應用程式中編寫的指令碼,那麼本書前半部內容是實用的語言核心。而在指定 網頁瀏覽器的章節,也許將會不適用於所編寫的指令碼。

1.5. Exploring JavaScript1.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 最明顯的方式是編寫個簡單的指令碼。網頁瀏覽器都以帶有用戶端 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:

這段代碼雖然可能暫時還看不明白,但是沒什麼關係--你只需把上面的代碼輸入進去後,在 網頁瀏覽器中開啟本地檔案: 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 中最後一個運算式的值會轉換為字串並在 網頁瀏覽器中當作新文檔顯示出來。比如,在 網頁瀏覽器的地址欄[1]( Location field)中輸入下面的 JavaScript URL 來測驗 JavaScript 的運算子、語句:

譯註1:Location field :IE和google Chrome稱為:地址欄。Firefox 稱為:位置。

javascript:5%2javascript: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 網頁瀏覽器中也可以在 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)

翻譯:《JavaScript 權威指南(第5版)》第一章(一)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.