Table of Contents

12.11 Simulating Namespaces

A namespace is a unique area of a program within which all identifiers are guaranteed to be unique. It lets a program use, say, both Company X's and Company Y's unique Ball classes without conflicts (i.e., without one class declaration overwriting the other). ActionScript in Flash MX does not have formal support for namespaces, but we can simulate them by creating a unique global object and defining all of a program's identifiers on it (as we saw in the earlier Section 12.9.2). Typically, the unique global object is named after a domain name, because domains 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");

Table of Contents