AS3 Namespaces

Actionscript

Was just browsing the AS3 specification, and thought this new feature was pretty interesting.

Namespace example, copied below.

AS:


package actors {
    public namespace English
    public namespace French
    public class BilingualGreeter {
        English function hello() {
            trace(“hello, world”)
        }
        French function hello() {
            trace(“bonjour, le monde”)
        }
    }
}
import actors.*
var greeter : BilingualGreeter = new BilingualGreeter
use namespace English     // Make all identifiers in the English namespace
                          // visible
greeter.hello()           // Invoke the English version
greeter.French::hello()   // Invoke the French version

Basically, you can switch the way certain methods (and properties) work with a single command. I can think of a few ways in which this would be useful.

Sure, you could do this in AS2 by setting a variable and executing different functions manually. But this seems way more elegant to me.

Imagine that you are selling the same product to a few clients, but one pesky client wants certain elements buried deep within your code to work a bit differently (”Yeah.. can I have this list box wobble when you hover over it?”). With namespaces, you could add this functionality without disturbing your original (and more sensible) code, and make your clients happy without having a variable for each of these modifications.

The AS3 specification draft describes some other uses for namespaces, but I’d be interested to know of other people’s inventive ideas.

Incidentally, I also noticed the distinct lack of semi-colons in the specs. :)

This entry was posted on Wednesday, March 1st, 2006 at 12:37 am and is filed under Actionscript. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

2 Responses to “AS3 Namespaces”

  1. Campbell Says:

    Damn thats gonna be handy, I can see uses already, does it work with interface’s?

  2. Xpb7 Says:

    I don’t really get it. Isn’t it easier just to say hello creating constructor’s attribute which would define a language? Like this:

    package actors {
    public class BilingualGreeter {
    public function BilingualGreeter(langId: uint) {
    if (langId == 1) {
    trace(“hello, world”)
    } else {trace(“bonjour, le monde”)}

    }
    }

    import actors.*
    var greeter : BilingualGreeter = new BilingualGreeter(1); //English
    greeter = new BilingualGreeter(2); //French

Leave a Reply