JavaScript进阶教程(第五课第五部分)

信息分类:进阶教程 来源:Internet 作者:转载并修改 返回首页

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

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

    第一步:写注释

    //function beSassy()
    //  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快速运行。

相关资源