If you’ve ever used namespaces in AS3 you’ve probably done something like trying to parse XML containing one or more namespaces which arguably is a pain most of the time. Namespaces however have some other uses that can be quite helpful.
For the examples I’ve defined two namespaces in an external class, while you can define namespaces in-line it isn’t very reusable.
class Environment {
namespace development = "dev";
namespace production = "prod";
}
Using the same configuration file for several different environments
(this also allows you to switch the environment at run-time)
var data:XML =
<config xmlns:dev="dev" xmlns:prod="prod">
<dev:gateway>http://local-server/gateway</dev:gateway>
<prod:gateway>http://www.client-server.com/gateway</prod:gateway>
</config>;
// Directly referencing the namespace
var ns:Namespace = Environment.development;
trace(data.ns::gateway); // http://local-server/gateway
// Using a specificed namespace
use namespace Environment.production;
trace(data.gateway); // http://www.client-server.com/gateway
Make functions perform differently depending on environment
Environment.production function doSomething():void {
trace("Production Parrot");
}
Environment.development function doSomething():void {
trace("Development Dino");
}
// Using a namespace adds it to the list of namespaces to look up, it lasts for a code block
use namespace Environment.development;
doSomething();
// use namespace Environment.production; // This won't work since the reference to the function is ambiguous
// However this will since the namespace list is only valid for one code block.
function someFunction():void {
use namespace Environment.production;
test(); // Production Parrot
}
someFunction();