Skip to Content
JavaScript: The Good Parts
book

JavaScript: The Good Parts

by Douglas Crockford
May 2008
Intermediate to advanced
172 pages
4h 54m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Good Parts

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 = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern JavaScript for the Impatient

Modern JavaScript for the Impatient

Cay S. Horstmann
Head First JavaScript Programming

Head First JavaScript Programming

Eric T. Freeman, Elisabeth Robson
Learn JavaScript

Learn JavaScript

Shaun Wassell

Publisher Resources

ISBN: 9780596517748Supplemental ContentCatalog PageErrata