将 JavaScript 模块添加到全局范围的跨平台方法是什么?
我正在查看 store.js 的源代码,特别是它如何将自身添加到全局范围:
if (typeof module != 'undefined') { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { this.store = store }
我理解最后一个语句 this.store = store
,但是其他语句怎么样?什么是 module
和 define
函数? this.store = store
不是已经可以在所有浏览器上运行了吗?
更一般地说,将模块添加到全局范围的正确的跨浏览器方法是什么?
I was having a look at the source code of store.js, in particular how it adds itself to the global scope:
if (typeof module != 'undefined') { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { this.store = store }
I understand the last statement this.store = store
, but how about the other ones? What are the module
and define
functions? Won't this.store = store
already work on all the browsers?
More generally, what is the correct, cross-browser way, to add a module to the global scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一种情况是 CommonJS,它最常用于 Node.js,是 AMD 的一种风格(< a href="https://github.com/amdjs/amdjs-api/wiki/AMD" rel="nofollow">异步模块定义)。模块是一个 JavaScript 文件,它使用定义的全局模块对象来执行。该文件设置为 module.exports 的任何内容都将可供应用程序的其他部分使用,并且文件中的其他所有内容都将仅对该模块保持私有。这是关于它的好博客文章。
第二个是针对 AMD 的另一种风格,最常使用 requirejs 实现。它与 CommonJs 的想法非常相似,但在浏览器中更常见。 Dojo 框架是基于 amd 的框架的一个很好的例子。 Jquery 社区也大力支持 amd。
define
告诉 amd 系统您正在为它提供一个模块,应用程序的其余部分可以使用require
引入该模块。最终版本是在普通简浏览器中运行的常见场景。
this
很可能是 DOMWindow,因此 store 对象在整个网页上成为全局对象。The first case is for CommonJS, which is most notably used in Node.js and is a flavor of AMD (Asynchronous Module Definition). A module is a JavaScript file that gets executed with a global module object defined. Whatever that file sets to
module.exports
will be available to other parts of the app, and everything else in the file will remain private to just that module. Here is a good blog post on it.The second one is for another flavor of AMD, which is most commonly implemented with requirejs. It's a very similar idea to CommonJs, but is more commonly found in the browser. The Dojo framework is one good example of an amd based framework. The Jquery community is getting behind amd a lot as well.
define
tells the amd system that you are giving it a module that the rest of the app can pull in by usingrequire
.The final version is the common scenario of running in a plain jane browser.
this
is most likely DOMWindow, and thus the store object becomes global across the whole webpage.