Though JavaScript provides no actual module construct yet, objects can be used to create publicly accessible subnamespaces, and functions can be used to create an isolated, private namespace inside of a module.
Functions are the only things in JavaScript that create a new scope.
A convenient alternative is to declare an object (conventionally named exports) and add properties to that whenever we are defining something that needs to be exported.
The module will claim a single global variable and wrap its code in a function in order to have its own private namespace. But this pattern still causes problems if multiple modules happen to claim the same name or if you want to load two versions of a module alongside each other.
CommonJS modules
we can create a system that allows one module to directly ask for the interface object of another module, without going through the global scope.
Our goal is a require function that, when given a module name, will load that module’s file (from disk or the Web, depending on the platform we are running on) and return the appropriate interface value.
a function readFile, which returns the content of a given file as a string.
execute this string as JavaScript code
Evaluating data as code
special operator eval, which will execute a string of code in the current scope. This is usually a bad idea because it breaks some of the sane properties that scopes normally have, such as being isolated from the outside world.
A better way of interpreting data as code is to use the Function constructor.
This takes two arguments: a string containing a comma-separated list of argument names and a string containing the function’s body.
Though it is possible to use the CommonJS module style when writing JavaScript for the browser, it is somewhat involved. The reason for this is that reading a file (module) from the Web is a lot slower than reading it from the hard disk
One way to work around this problem is to run a program like Browserify on your code before you serve it on a web page.
Another solution is to wrap the code that makes up your module in a function so that the module loader can first load its dependencies in the background and then call the function, initializing the module, when the dependencies have been loaded. That is what the Asynchronous Module Definition (AMD) module system does.
There are two popular, well-defined approaches to such modules.
CommonJS Modules and revolves around a require function that fetches a module by name and returns its interface.
AMD and uses a define function that takes an array of module names and a function and, after loading the modules, runs the function with their interfaces as arguments.