dojo 1.7 AMD 框架有什么好处?
我一直在此处阅读有关 dojo 1.7 加载程序如何使用 AMD API/框架的信息和这里,我在其中一张幻灯片上看到了这句话:“AMD(的)最大的好处正如某些人可能认为的那样,无法按需加载脚本,最大的好处是代码组织/模块化的增加以及对全局/命名空间的需求的减少。”但我的问题是,是否可以通过使用普通的 js 函数来避免全局变量,如果您需要访问另一个函数的执行上下文(以及另一个函数的“私有”变量),也许可以使用 dojo.hitch() ?换句话说,除了异步加载你需要的东西之外,AMD框架还有什么好处呢?
I have been reading about how the dojo 1.7 loader uses an AMD API/framework here and here too, and I came across this quote on one of the slides: "AMD(’s) greatest benefit isn’t being able to load scripts on-demand, as some people may think, the greatest benefit is the increase of the code organization/modularity and also the reduced need for globals/namespacing." But my question is, can't global variables already be avoided by using normal js functions, and maybe dojo.hitch() if you need to access another function's execution context (and another function's 'private' variables)? Put another way, other than asynchronously loading only what you need, what is the benefit of the AMD framework?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AMD 的好处是拥有模块系统的好处,类似于其他语言中的命名空间系统。在 JavaScript 中,我们经常使用全局变量来伪造这一点,但模块具有许多特定的好处:
--- 来自 CommonJS Modules/1.1.1 规范,它开始了这一切。
这里的关键是进出口设施。以前,每个人都使用全局变量(例如
window.jQuery
、window._
等)来临时执行此操作。要获得 jQuery 的导出功能,您必须知道这个神奇的名称,希望没有人与它发生冲突,并确保 jQuery 脚本在您的脚本之前加载。没有办法以声明方式指定对 jQuery 的依赖,并且 jQuery 也没有办法说“这就是我导出的”,除了将它们填充到全局window.jQuery
对象中。模块格式解决了这个问题:每个模块导出特定的功能,例如
,每个模块都可以需要特定的其他模块,例如
关于为什么 AMD 应该成为首选的模块系统,RequireJS——一个很像 Dojo 的 AMD 加载器——写了 一篇博客文章详细说明了为什么他认为 AMD 是最好的。
The benefits of AMD are the benefits of having a module system, analogous to a namespace system in other languages. In JavaScript, we often faked this with global variables, but modules give a number of specific benefits:
--- From the CommonJS Modules/1.1.1 spec, which started it all.
Key here is the import and export facilities. Previously everyone was doing this ad-hoc, with globals (like
window.jQuery
,window._
, etc.). To get at jQuery's exported functionality, you had to know the magic name, hope nobody conflicted with it, and be sure that the jQuery script was loaded before your script. There was no way of declaratively specifying your dependency on jQuery, and jQuery had no way of saying "this is what I export" apart from just stuffing them onto a globalwindow.jQuery
object.A module format fixes this: each module exports specific functions, e.g.
and each module can require specific other modules, e.g.
On why AMD should be the module system of choice, James Burke, the author of RequireJS---an AMD loader much like Dojo has---wrote a blog post detailing why he thinks AMD is the best.