AS3 Namespaces
Was just browsing the AS3 specification, and thought this new feature was pretty interesting.
Namespace example, copied below.
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.


March 1st, 2006 at 7:00 am
Damn thats gonna be handy, I can see uses already, does it work with interface's?
October 29th, 2008 at 8:35 am
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
July 3rd, 2009 at 4:29 pm
I agree with Xpb7 that it is easier to use a param value to switch between the languages. Moreover, I think doing so would open up to a more solid debugging process and perhaps give more extensibility.
I'm curious to here a response from RazorBerry though.
July 14th, 2009 at 7:21 am
I don't really get it.
October 28th, 2009 at 10:06 am
Xpb7 you need to learn more, you sound like a n00b.