Module
We can use functions and closure to make modules. A module is a function or object that presents an interface but that hides its state and implementation. By using functions to produce modules, we can almost completely eliminate our use of global variables, thereby mitigating one of JavaScript's worst features.
For example, suppose we want to augment String
with a deentityify method. Its job is to look for
HTML entities in a string and replace them with their equivalents. It makes sense to
keep the names of the entities and their equivalents in an object. But where should
we keep the object? We could put it in a global variable, but global variables are
evil. We could define it in the function itself, but that has a runtime cost because
the literal must be evaluated every time the function is invoked. The ideal approach
is to put it in a closure, and perhaps provide an extra method that can add
additional entities:
String.method('deentityify', function ( ) { // The entity table. It maps entity names to // characters. var entity = { quot: '"', lt: '<', gt: '>' }; // Return the deentityify method. return function ( ) { // This is the deentityify method. It calls the string // replace method, looking for substrings that start // with '&' and end with ';'. If the characters in // between are in the entity table, then replace the // entity with the character from the table. It uses // a regular expression (Chapter 7). return this.replace(/&([^&;]+);/g, function (a, b) { var r = ...