Javascript file organization and design

后端 未结 3 1010
梦如初夏
梦如初夏 2021-02-14 07:28

Really getting into web development and in particular JS so I was wondering what were the best practices in terms of JS file organization and delegation of responsibilities. I a

3条回答
  •  星月不相逢
    2021-02-14 07:59

    The best way to handle multiple JavaScript files is to design them like modules. One main JavaScript file should act as a sort of bootloader which kicks off things by setting up your "namespace" (quoted since JavaScript doesn't have classes). Example:

    var myNamespace = {};
    

    In each of your modules, you extend the "namespace". This has two benefits:

    • Minimizes globals. In this case, you will have a single global.
    • Easy to mix and match (and reuse) modules, if designed correctly.

    Also see this for implementation details: https://stackoverflow.com/a/3722845/221061

提交回复
热议问题