A module’s public API is the object and methods it exposes to other code. It provides access to module functionality while keeping internal variables hidden from outside modification. section 11.1 section 11.1.1
A function-based module separates its public API from its internals:
- The module function’s scope holds private variables and functions. section 11.1.1
- The function returns an object containing the methods other code can call. section 11.1.1
- Closures let those methods continue using internal variables after the module function finishes. section 11.1.1
Listing 11.1. The module pattern
const MouseCounterModule = function() { #A
let numClicks = 0; #B
const handleClick = () => { #C
alert(++numClicks); #C
}; #C
return { #D
countClicks: () => { #D
document.addEventListener("click", handleClick); #D
} #D
}; #D
}();
assert(typeof MouseCounterModule.countClicks === "function", #E
"We can access module functionality"); #E
assert(typeof MouseCounterModule.numClicks === "undefined" #F
&& typeof MouseCounterModule.handleClick === "undefined" , #F
"We cannot access internal module details"); #F
The click-counter module exposes countClicks while keeping numClicks and handleClick inside its function scope. section 11.1.1
A module’s public API can also be extended by passing it to another immediate function and adding methods. The added functionality has its own internal variables, separate from those of the original module. section 11.1.1
