Assigning and Passing Namespace Values

Because every namespace is represented by an instance of the Namespace class, namespaces can be assigned to variables or array elements, passed to methods, returned from methods, and generally used like any other object. This flexibility lets us:

  • Pass a namespace from one scope to another

  • Choose between multiple namespaces dynamically at runtime

These activities are critical to namespace usage in ActionScript. Let's see how.

Assigning a Namespace Value to a Variable

To assign a namespace value to a variable, we use the same assignment syntax we'd use with any other value. For example, the following code assigns the namespace value in fruit to the variable currentItemType (recall that a namespace value is a Namespace object):

// File fruit.as
package {
  namespace fruit = "http://www.example.com/games/kidsgame/fruit";
}

// File Items.as
package {
  public class Items {
    // Assign the value in fruit to currentItemType
    private var currentItemType:Namespace = fruit;
  }
}

A variable referencing a Namespace object can be used to form a qualified identifier. For example, consider the following variable definition:

fruit var orange:String = "Round citrus fruit";

To refer to that variable, we can use either the expression fruit::orange or the expression currentItemType::orange. By changing the value of currentItemType to some other namespace, we can dynamically adjust the meaning of the identifier currentItemType::orange, and of all other methods and variables qualified ...

Get Essential ActionScript 3.0 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.