网络编程
位置:首页>> 网络编程>> JavaScript>> JavaScript程序编码规范[译](2)

JavaScript程序编码规范[译](2)

作者:cloudwater  发布时间:2009-07-20 17:54:00 

标签:JavaScript,编程,规范

函数声明

所有的函数在使用前进行声明。 内函数的声明跟在var语句的后面。这样可以帮助判断哪些变量是在函数范围内的。

函数名与((左括号)之间不应该有空格。) (右括号)与 开始程序体的{(左大括号)之间应插入一个空格。函数程序体应缩进四个空格。 }(右大括号)与声明函数的那一行代码头部对齐。

function outer(c, d) {
var e = c * d;
function inner(a, b) {
return (e * a) + b;
}
return inner(0, 1);
}

下面这种书写方式可以在JavaScript中正常使用,因为在JavaScript中,函数和对象的声明可以放到任何表达式允许的地方。且它让内联函数和混合结构具有最好的可读性。

function getElementsByClassName(className) {
var results = [];
walkTheDOM(document.body, function (node) {
var a;                  // 类名数组
var c = node.className; // 节点的类名
var i;                  // 循环计数器
// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.
if (c) {
a = c.split(' ');
for (i = 0; i < a.length; i += 1) {
if (a[i] === className) {
results.push(node);
break;
}
}
}
});
return results;
}

如果函数是匿名函数,则在function和((左括号)之间应有一个空格。如果省略了空格,否则会让人感觉函数名叫作 function。

div.onclick = function (e) {
return false;
};
that = {
method: function () {
return this.datum;
},
datum: 0
};

尽量不使用全局函数。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com