Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

276 CHAPTER 6 Essential JavaScript and jQuery


FIGURE 6 -7 he use of getters to expose read-only data as a good compromiseT

Implementing namespaces


One problem to watch for is the pollution of the global namespace. As your program gets
larger and libraries are added, more entries are added to the global object. How can you
minimize this global namespace pollution?
JavaScript doesn’t have a namespace keyword, but you can implement the equivalent of a
namespace by using techniques that are similar to those used to create objects. Consider the
following code sample.
var vehicleCount = 5;

var vehicles = new Array();

function Car() { }
function Truck() { }

var repair = {
description: 'changed spark plugs',
cost: 100
};
This code sample places five entries in the global namespace, and as the application grows,
this global namespace pollution also grows. You can implement the namespace pattern to
solve the problem. The following example shows the creation of an object that contains the
five items from the previous example.
Free download pdf