dongwei5794 2012-04-26 00:13
浏览 7
已采纳

是否最好在代码的开头或结尾定义类和函数?

The Javascript tutorial I follow always defines before using, but my PHP book always defines at the end, and in fact points out that this is considered good practice.

Is there a reason to do it one way or the other?

  • 写回答

3条回答 默认 最新

  • dou1908 2012-04-26 00:19
    关注

    If you have inline code executing (e.g. executing as it is loaded), then global variables must be defined before the code that uses them.

    Functions can be defined in whatever order you think makes the code the most tidy and easiest to read.

    For example, in this code:

    foo();
    
    function foo() {
        alert(x);
    }
    
    var x = 4;
    ​
    

    The call to foo() will alert undefined because x does not yet have a value when foo() is called, but you will notice that foo can be called in code that appears before the function definition because all functions are loaded before any code is actually executed.

    As for a best practice, I think it makes sense to organize your code in the best way you can find that puts modules of related functionality together, but the order is not generally material. I trust you realize that javascript doesn't have anything that is actually a class. It can use function objects and prototypes to simulate some class-like behavior that other languages have, but it doesn't really have classes as it's objects are based on prototypes, not classes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序