12.11 Simulating Namespaces

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 12.  Objects and Classes

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");
     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

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