
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
322
|
Chapter 12: Objects and Classes
are guaranteed to be unique. For example, to create a namespace for my classes I use
the following code (my site’s domain is moock.org):
if (_global.org = = undefined) {
_global.org = new Object( );
}
if (_global.org.moock = = undefined) {
_global.org.moock = new Object( );
}
This code appears in all my classes (each class has the responsibility of creating the
namespace if it doesn’t already exist.) Here’s a convenient function, AsSetupPackage( ),
that you can use to create a namespace for your own classes:
_global.AsSetupPackage = function (path) {
var a = path.split('.');
var o = _global;
for (var i = 0; i < a.length; i++) {
var name = a[i];
if (o[name] = = undefined) {
o[name] = new Object( );
}
o = o[name];
}
}
Within each class, you can use AsSetupPackage( ) to create the class’s namespace, as
follows:
AsSetupPackage("com.yourdomain");
For example, I use:
AsSetupPackage("org.moock");
The Multiple-Choice Quiz, OOP Style
Now that you understand the principles of OOP, let’s return to our multiple-choice
quiz example to see them in action. The source code for our OOP quiz is too long to
present here, but it can be downloaded from the Code Depot. The important part of
the application is its object design, listed next. Even without seeing the code in