One of the purpose of a namespace in AS3 is not only to provide scoping mechanism but also to avoid name conflicts. Assume you’re going to create a StringUtility class that consists of multiple different methods called “trim” developed by your friends namely Abraham and Thomas.

Create a project folder named NamespaceTest.

Inside that directory, create a namespace file called abraham.as like so:

package{
	public namespace abraham = "Abraham Lincoln";
}

Then create a second namespace file called thomas.as like so:

package{
	public namespace thomas = "Thomas Jefferson";
}

Create a class file called StringUtility.as like so:

package{
    public final class StringUtility{
        public function StringUtility(){
           trace(StringUtility.abraham::trim(""));
        }
        //
        abraham static function trim(value:String):String{
            return "a";
        }
        thomas static function trim(value:String):String{
            return "b";
        }
    }
}

Then create a file called NamespaceTest.fla and place this in the Actions Panel:

trace(StringUtility.thomas::trim(""));

A namespace not only allows you to have a multiple function names in a single class but also provides another scoping feature on how to access a method without making method public. To use the trim methods on another projects, just import the namespace itself, which would deliberately make the method look like public. Assuming that you already know name your packages and set your Flash IDE.

SeparateNamespaceTest.fla is on a separate project directory.

import  abraham;
import thomas;
//
trace(StringUtility.::abraham(""));

If you only plan to use your namespaces internally and directly access your multiple methods, declare your namespaces like so inside the class:

package{
    public final class StringUtility{
        public namespace abraham = "Abraham Lincoln";
        public namespace thomas = "Thomas Jefferson";
        //
        public function StringUtility(){
           StringUtility.abraham::trim("");
        }
        //
        abraham static function trim(value:String):String{
            return "a";
        }
        thomas static function trim(value:String):String{
            return "b";
        }
    }
}

I hope that made it clear for you as to what the basic purpose of a namespace in AS3 is.

Advertisements