Java Reference
In-Depth Information
stored in a global variable. This keeps the module in its own private namespace (the vari-
able it is assigned to), which helps stop any methods from clashing with other methods
having the same name.
For example, we could create a Stats module based on the sum() , mean() , and
standardDeviation() functions we created in Chapter 11 :
var Stats = (function() {
"use strict";
// square and sum are private functions
function square(x) {
return x * x;
}
function sum(array, callback) {
if (typeof callback === "function") {
array = array.map(callback);
}
return array.reduce(function(a,b) { return a + b; });
}
function mean(array) {
return sum(array) / array.length;
}
function sd(array) {
return sum(array,square) / array.length -
square(mean(array));
}
// public functions are exported as methods of an object
return {
mean: mean,
standardDeviation: sd
};
}());
 
Search WWH ::




Custom Search