Javascript文件组织和设计 [英] Javascript file organization and design
问题描述
真正进入Web开发,尤其是JS,所以我想知道JS文件组织和职责委派方面的最佳实践是什么。我问这个是因为我有这种结构是有意义的:
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 ask this because it would make sense to me to have this kind of structure:
- 主页(PHP)(包括对a的引用)中央JS文件)
- MAIN Javascript文件(包含对一个文件的引用,该文件仅包含命名空间或B类中的错误代码)
虽然这对我有意义,但我想知道我的观点是否错误,因为你不能自然地将JS文件包含在另一个中,除非你做了几个技巧(不,不是在谈论jQuery)。技巧可能意味着这不仅仅是因为它不适合语言的最佳实践,但在跨域问题方面并非总是如此。因此,在我深入研究草率设计之前,我只是好奇你们是如何分担责任的,或者只是将所有内容整合到一个文件中。
While this makes sense to me, I am wondering if I am wrong in my view considering the fact that you can't naturally include a JS file into another unless you do a couple tricks (no, not talking about jQuery). Tricks may mean that this isn't done simply because it doesn't fit with the best of practices for a language but it's not always the case in terms of cross-domain issues. So before I go too deep into sloppy design, I was just curious how you guys divided up the responsibilities or just slopped everything together into one file.
推荐答案
处理多个JavaScript文件的最佳方法是将它们设计为模块。一个主要的JavaScript文件应该作为一种引导程序,它通过设置你的命名空间来引发事情(引用因为JavaScript没有类)。示例:
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:
- 最小化全局变量。在这种情况下,您将拥有一个全局。
- 如果设计正确,易于混合和匹配(和重复使用)模块。
另见实现细节: https://stackoverflow.com/a/3722845/221061
这篇关于Javascript文件组织和设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!