JavaScript高级教程 - 第五课
Thau

第五页:好的编程实践

编好程序的关键是程序是写给人的,不是写给计算机的。如
果你能明白其他人或许会阅读你的JavaScript,你就会写更
清晰的代码。代码越清晰,你就越不容易犯错误。机灵的代
码是可爱的,但就是这种机灵的代码会产生错误。最好的经
验法则是KISS,即Keep It Simple,Sweetie(保持简单,可爱)。

另一个有帮助的技术是在写代码之前作注释。这迫使你在动
手之前先想好。一旦写好了注释,你就可以在其下面写代码。
下面是一个用这种方法写函数的例子:

第一步:写注释

//function beSassy()

//  beSassy asks for a user's name, chooses a random 

//  insult and returns an alert box with the user's name and the

//  insult.

function beSassy()

{

	//  first write a list of insults

	//



	//  next get the user's name

	//



	//  then choose a random insult  

	//



	//  finally, return the personalized sass

	//

}

第二步:填充代码

//function beSassy()

//  beSassy asks for a user's name, chooses a random 

//  insult and returns an alert box with the user's name and the

//  insult.

function beSassy()

{

	//  first write a list of insults

	//

	var the_insult_list = new Array;

	the_insult_list[0] = "your shoe lace is untied";

	the_insult_list[1] = "your mama!";

	the_insult_list[2] = "it's hard to be insulting";



	//  next get the user's name

	//

	var the_name = prompt("What's your name?", "");



	//  then choose a random insult  

	//

	var the_number =  Math.random() * 5;

	var insult_number = parseInt(the_number);

	var the_insult = the_insult_list[insult_number];



	//  finally, return the personalized sass

	//

	alert("Hey " + the_name + " " + the_insult);

}

这种先写注释的策略不仅迫使你在写代码前思考,而且
使编码的过程看起来容易些 - 通过把任务分成小的,
易于编码的各个部分,你的问题看起来就不太象珠穆朗
玛峰,而象一群令人愉悦的起伏的小山。

最后...

总以分号结束你的每一条语句。

虽然并不是严格必需,你应该养成以分号结束每一条语
句的习惯,这样可以避免这行后面再有代码。忘了加
分号,下一行好的代码会突然产生错误。

把变量初始化为“var”,除非你有更好的理由不这样做。

用“var”把变量局域化可以减少一个函数与另一个不相
关函数相混淆的机会。

好了,既然你已经知道了如何编码,下面就让我们学习怎样使
你的JavaScript快速运行。>>

JavaScript高级教程
第一页 JavaScript高级教程- 5
第二页 打印变量
第三页 一般性程序错误
第四页 修正错误
第五页 好的编程实践
第六页 按速度优化JavaScript代码
第七页 下面讲什么?

[第1课][第2课][第3课][第4课][第5课]


本文根据 网猴 相关文章改编,版权归原作者所有。