Java Reference
In-Depth Information
This function will return an object that's assigned to the variable Stats . It has two public
methods, mean() and standardDeviation() . The module also has two private
functions, square() and sum() , that are not returned, so are not publicly available to
the module (they are just used internally by other methods). The public methods are called
using the Stats object:
<< 2
<< 0.666666666666667
To use a module in a web page, include the file in which it's saved in script tags on the
<script src="stats.js"></script>
<script src="scripts.js"></script>
Two standard ways of implementing JavaScript modules have emerged: the CommonJS
Module pattern and the Asynchronous Module Definition pattern. Unfortunately, these pat-
terns are incompatible with each other. An example of each follows, where they are both
capable of keeping modules in their own namespace, and adding multiple methods as well
as submodules and dependencies on other modules.
CommonJS Modules
CommonJS Modules have a compact syntax that is designed for synchronous loading. It
is how modules are implemented in Node.js.
A module is created in a separate file and the module.exports method is used to make
any functions available to other files. For example, we could create a module for the ran-
dom() function that we created in Chapter 11 by first placing the following code in a file
called random.js:
module.exports = function(a,b) {
if(b===undefined) b = a, a = 1; // if only one argument
Search WWH ::

Custom Search