2007年5月31日星期四

Support for Namespaces

ActionScript 3 now supports namespaces. Namespaces in AS3 are similar to namespaces in XML and provide a way to separate code in to separate "spaces" or collections identifiable through a name (namespace). Namespaces in this respect act much like packages. In the same manner that packages allow you to have different classes with the same name in one application (only defined in different packages), namespaces allow you to have different methods with the same name in one class (defined in different namespaces). Though you may not have known it, chances are you've already been using namespaces. Predefined namespaces include public, private, protected, and internal.

When you use a namespace, you have to declare it just like you declare any other class member. Namespaces are declared using the namespace keyword (namespace Keyword). Once declared you can use it to separate members into different namespaces. Ex:

ActionScript Code:

package {

public class UsingNameSpaces {

public namespace company;
public namespace individual;

company var value:
int = 10;
individual var value:
int = 2;

public function UsingNameSpaces(){
}

company function showValue() {
}

individual function showValue() {
}
}
}


Two namespaces were used here, company and individual. They were used to defined a value variable and a showValue method - one for each namespace. Though they have the same names, since they are in different namespaces, they are allowed.

Additionally, namespaces can otionally be defined with a namespace uri when declared in the class:

ActionScript Code:

package {

public class UsingNameSpaces {

public namespace company = "http://www.example.com/company";
public namespace individual = "http://www.example.com/individual";

company var value:
int = 10;
individual var value:
int = 2;

public function UsingNameSpaces(){
}

company function showValue() {
}

individual function showValue() {
}
}
}

0 评论: