Chapter 10. Modules and Namespaces

In JavaScript’s early years, it was often used in small, simple scripts embedded directly in web pages. As web browsers and web standards have matured, JavaScript programs have become longer and more complex. Today, many JavaScript scripts depend on external modules or libraries of JavaScript code.[*]

At the time of this writing, there is an effort underway to create a collection of reusable, open source JavaScript modules. The JavaScript Archive Network (JSAN) is fashioned after the Comprehensive Perl Archive Network (CPAN) and hopes to do for JavaScript what CPAN did for the Perl language and community. See http://www.openjsan.org to learn more and find code.

JavaScript does not provide any language features for creating or managing modules, so writing portable, reusable modules of JavaScript code is largely a matter of following some basic conventions, which are described in this chapter.

The most important convention involves the use of namespaces to prevent namespace collisions—which is what happens when two modules define global properties with the same name: one module overwrites the properties of another, and one or both modules operate incorrectly.

Another convention involves module initialization code. This is particularly important in client-side JavaScript because modules that manipulate a document in a web browser often need to have code triggered when the document finishes loading.

The following sections discuss namespaces and ...

Get JavaScript: The Definitive Guide, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.