简体   繁体   English

将JavaScript模块添加到全局范围的跨平台方法是什么?

[英]What is the cross-platform way to add a JavaScript module to the global scope?

I was having a look at the source code of store.js , in particular how it adds itself to the global scope: 我正在查看store.js的源代码,特别是它如何将自己添加到全局范围:

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? 我理解最后一句话this.store = store ,但其他的怎么样? What are the module and define functions? 什么是moduledefine功能? Won't this.store = store already work on all the browsers? this.store = store不会在所有浏览器上运行吗?

More generally, what is the correct, cross-browser way, to add a module to the global scope? 更一般地说,将模块添加到全局范围的正确的跨浏览器方式是什么?

The first case is for CommonJS , which is most notably used in Node.js and is a flavor of AMD ( Asynchronous Module Definition ). 第一种情况是CommonJS ,它最常用于Node.js,是AMD( 异步模块定义 )的一种风格。 A module is a JavaScript file that gets executed with a global module object defined. 模块是一个JavaScript文件,可以使用定义的全局模块对象执行。 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. 无论该文件设置为module.exports将可用于应用程序的其他部分,文件中的其他所有内容将仅保留为该模块的私有。 Here is a good blog post on it. 这是一篇很好的博客文章

The second one is for another flavor of AMD, which is most commonly implemented with requirejs . 第二个是AMD的另一种风格,最常用的是requirejs It's a very similar idea to CommonJs, but is more commonly found in the browser. 这与CommonJs非常相似,但在浏览器中更常见。 The Dojo framework is one good example of an amd based framework. Dojo框架是基于amd的框架的一个很好的例子。 The Jquery community is getting behind amd a lot as well. Jquery社区也越来越落后于amd。 define tells the amd system that you are giving it a module that the rest of the app can pull in by using require . define告诉amd系统你给它一个模块,应用程序的其余部分可以使用require引入。

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. this很可能是DOMWindow,因此商店对象在整个网页上变得全球化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM