Understanding classes and scope

When you move ActionScript code into classes, you might have to change how you use the this keyword. For example, if you have a class method that uses a callback function (such as the LoadVars class's onLoad() method), it can be difficult to know whether the this keyword refers to the class or to the LoadVars object. In this situation, it might be necessary to create a pointer to the current class, as the next example shows.

To understand scope and external class files:

  1. Select File > New and then select ActionScript File, and then click OK.
  2. Type or paste the following code into the Script window:
    /**
        Product class
        Product.as
    */
    class Product {
      private var productsXml:XML;
      // constructor
      // targetXmlStr - string, contains the path to an XML file
      function Product(targetXmlStr:String) {
        /* Create a local reference to the current class. 
           Even if you are within the XML's onLoad event handler, you 
           can reference the current class instead of only the XML packet.
        */
        var thisObj:Product = this;
        // Create a local variable, which is used to load the XML file.
        var prodXml:XML = new XML();
        prodXml.ignoreWhite = true;
        prodXml.onLoad = function(success:Boolean) {
          if (success) {
            /* If the XML successfully loads and parses, 
               set the class's productsXml variable to the parsed 
               XML document and call the init function.
            */
            thisObj.productsXml = this;
            thisObj.init();
          } else {
            /* There was an error loading the XML file. */
            trace("error loading XML");
          }
        };
        // Begin loading the XML document.
        prodXml.load(targetXmlStr);
      }
      public function init():Void {
        // Display the XML packet.
        trace(this.productsXml);
      }
    }
    

    Because you are trying to reference the private member variable within an onLoad handler, the this keyword actually refers to the prodXml instance and not the Product class, which you might expect. For this reason, you must create a pointer to the local class file so that you can directly reference the class from the onLoad handler. You can now use this class with a Flash document.

  3. Save the previous ActionScript code as Product.as.
  4. Create a new Flash document named testProduct.fla in the same directory.
  5. Select Frame 1 of the main Timeline.
  6. Type the following ActionScript into the Actions panel:
    var myProduct:Product = new Product("http://www.helpexamples.com/crossdomain.xml");
    
  7. Select Control > Test Movie to test this code in the test environment.

    The contents of the specified XML document appear in the Output panel.

Another type of scope you encounter when working with these classes is static variables and static functions. The static keyword specifies that a variable or function is created only once per class rather than being created in every instance of that class. You can access a static class member without creating an instance of the class by using the syntax someClassName.username. For more information on static variables and functions, see About public, private, and static methods and properties (members) and Using class members.

Another benefit of static variables is that static variables don't lose their values after the variable's scope has ended. The following example demonstrates how you can use the static keyword to create a counter that tracks how many instances of the class Flash has created. Because the numInstances variable is static, the variable is created only once for the entire class, not for every single instance.

To use the static keyword:

  1. Select File > New and then select ActionScript File, and then click OK.
  2. Type the following code into the Script window:
    class User {
      private static var numInstances:Number = 0;
      public function User() {
        User.numInstances++;
      }
      public static function get instances():Number {
        return User.numInstances;
      }
    }
    

    The previous code defines a User class that tracks the number of times the constructor has been called. A private, static variable (User.numInstances) is incremented within the constructor method.

  3. Save the document as User.as.
  4. Select File > New and then select Flash Document to create a new FLA file, and save the FLA file in the same directory as User.as.
  5. Type the following ActionScript code in Frame 1 of the Timeline:
    trace(User.instances); // 0
    var user1:User = new User();
    trace(User.instances); // 1
    var user2:User = new User();
    trace(User.instances); // 2
    

    The first line of code calls the static instances() getter method, which returns the value of the private static numInstances variable. The rest of the code creates new instances of the User class and displays the current value returned by the instances() getter method.

  6. Select Control > Test Movie to test the documents.

For information on using the this keyword in classes, see About using the this keyword in classes.


Flash CS3