문제

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?

도움이 되었습니까?

해결책

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 using 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top