2.4 在脚本中编写注释
养成在脚本中添加注释的习惯是一种很好的做法。JavaScript不会将插入的注释解释为脚本命令。尽管在编写脚本时它可能看起来非常清晰,但是如果你过几个月再看这个脚本,就可能觉得它很晦涩。注释有助于解释你为什么按照某种方式解决问题。对脚本进行注释的另一个原因是,别人可能希望重用和修改你的脚本,注释对他们也有帮助。
脚本2-4给出了两种脚本注释的示例。第一种用于比较长的多行注释。第二个示例显示如何编写单行注释。
脚本2-4 这里的代码演示如何给脚本加注释,注释有助于你和别人理解代码
/*
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!";
}
注意,我们没有给出这个示例的HTML,因为它与脚本2-2是相同的。从现在开始,如果HTML与前一个示例相比没有变化,我们就不再重复显示它。
对脚本进行注释的步骤如下:
(1) /*
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.
对于多行的注释,行开头的/*让JavaScript忽略此后的所有内容,直到注释的末尾为止。
(2) /*
这是注释的末尾。
(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! ";
}
这里是与前一个示例一样的脚本,但是加上了单行的注释。可以看到,单行的注释可以单独占据一行,也可以跟在代码行后面。在单行注释后面,同一行上不能再编写代码了;多行注释不能与代码同在一行上。
是的,我们也厌倦了“Hello, world!”示例,但这是传统,所有编程图书都以这个示例开始讲解。
现在就来看点儿新鲜的东西吧!







