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.[*]

[*] Core JavaScript does not have any mechanism for loading or including an external module of code. This is the responsibility of whatever environment the JavaScript interpreter is embedded within. In client-side JavaScript, it is done with the <script src=> tag (see Chapter 13). Other embeddings may provide a simple load( ) function for loading modules.

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 collisionswhich 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 initialization, and the chapter concludes with an extended example of a module of utility functions for working with modules.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net