注释
javascript支持单行和多行注释。注释被javascript引擎忽略,因此对程序的结果没有副总用。对于其他开发人员来说,注释是代码的文档。类似于JSDoc的库,它可以借助于注释产生项目文档页面,这样就非常有用了。
// Single and multi line comments.
// This is an example of a single line comment.
/*
* this is an example
* of a
* multi line
* comment.
*/
空白
空白也被javascript忽略。有许多工具程序,可以去掉程序所有的空白,降低整体的文件大小和提高网络延迟。得益于这类工具的好处,空白应尽可能的考虑以增强代码的可读性。
// Whitespace is insignificant.
var hello = "Hello";
var world = "World!";
// Semantic whitespace promotes readability.
// Readable code is good!
var foo = function() {
for ( var i = 0; i < 10; i++ ) {
alert( i );
}
};
foo();
// This is much harder to read!
var foo=function() {for(var i=0;i<10;i++){alert(i);}};foo();
保留字
有不少的保留字它们不能用于用户声明变量和函数。保留字中有些目前已经实现了,有些以备将来使用,其他的因为历史原因被当作保留字。保留字列表可以在这里找到,各保留字的深层解释可以在MDN javascript指南找到。
标识符
标识符给变量或函数一个名字以便将来可用通过该名字引用它们。标识符名必须遵守一些规则:
- 不能使用保留字
- 只能组合使用字母,数字,美元符号和下划线
- 首字母不能为数字
给标识符命名的最好实践是取一个相对有意义的名字,对于你和其他开发人员来说。
// Valid identifier names.
var myAwesomeVariable = "a";
var myAwesomeVariable2 = "b";
var my_awesome_variable = "c";
var $my_AwesomeVariable = "d";
var _my_awesome_variable_$ = "e";
变量定义
变量定义可以通过多个var语句,或者一个组合var语句。
// this works
var test = 1;
var test2 = function() { ... };
var test3 = test2( test );
// and so does this
var test4 = 1,
test5 = function() { ... },
test6 = test2( test );
变量可以只声明不赋值。只声明不赋值的变量的值为 undefined。
var x;
x === undefined; // true