Putting Comments in Scripts


It's a good idea to get into the habit of adding comments to your scripts. You do this by inserting comments that JavaScript won't interpret as script commands. While your script may seem perfectly clear to you when you write it, if you come back to it a couple of months later it may seem as clear as mud. Comments help to explain why you solved the problem in a particular way. Another reason to comment your script is to help other people who may want to re-use and modify your script.

Script 2.4 shows examples of two kinds of script comments. The first kind is for longer, multi-line comments. The second example shows how to do single-line comments.

Script 2.4. Here's how you can annotate your script with comments, which helps you and others understand your code.
[View full width]
  /*   This is an example of a long JavaScript comment. Note the characters at the beginning  and ending of the comment.   This script adds the words "Hello, world!" into the body area of the HTML page.   */   window.onload = writeMessage;   // Do this when page finishes loading   function writeMessage() {   // Here's where the actual work gets done   document.getElementById("helloMessage"). innerHTML = "Hello, world!";   }  

Note that we haven't included the HTML for this example, as it is the same as Script 2.2. From now on in the book, when the HTML hasn't changed from a previous example, we won't be printing it again.

To comment your script:

1.
[View full width]
 
[View full width]
/* This is an example of a long JavaScript comment. Note the characters at the beginning and ending of the comment. This script adds the words "Hello, world!" into the body area of the HTML page.



For multi-line comments, the /* at the beginning of the line tells JavaScript to ignore everything that follows until the end of the comment.

2.
*/

This is the end of the comment.

3.
 window.onload = writeMessage;   // Do this when page finishes loading function writeMessage() {   // Here's where the actual work gets done   document.getElementById ("helloMessage").innerHTML =  "Hello, world!"; } 

And here's the script again, as in the previous example, with single-line comments. As you can see here, single-line comments can be on a line by themselves , or they can follow a line of code. You can't have a line of code on the same line after a single-line comment, nor can you have a multi-line comment on the same line as code.

Yes, we're as tired of seeing this one as you are, but it's traditional for all code books to start off with the "Hello, world!" example.

So much for tradition.




JavaScript and Ajax for the Web(c) Visual QuickStart Guide
JavaScript and Ajax for the Web, Sixth Edition
ISBN: 0321430328
EAN: 2147483647
Year: 2006
Pages: 203

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net