Archives for November 2010...

(1 results found)

Dynamic Classes in ActionScript 3

Mon Nov 29 23:45:29 2010

Dynamic classes in AS3 are a cool feature of the language. They allow you to add properties to the dynamic class at run time, which is something that is not possible with other types of class. It is important to note however that dynamic class are a little more memory intensive, due to the fact that they create what is called a 'hash table' to store the properties/methods added at runtime.

The Dynamic Class - MyDynamicClass


package{	
   import flash.display.*;
	
   public dynamic class MyDynamicClass extends MovieClip{
      public var firstName:String = "Ben";
      private var age:String = "28";

      public function MyDynamicClass(){
			
      }
   }
}

Public Class Main (instantiates MyDynamicClass)


package{	
   import flash.display.*;
   import MyDynamicClass;
	
   public class Main extends MovieClip{
      private var d:MyDynamicClass = new MyDynamicClass();

      public function Main(){
         trace(d.firstName); // outputs "Ben";	
         trace(d.age); //outputs undefined

         d.gender = "Male";
         trace(d.gender); //outputs Male
         delete d.gender;
         trace(d.gender) //outputs undefined
      } 
   }
}

Looking at MyDynamicClass, you will notice that it contains 2 variables - firstName and age. The property firstname is accessible by Main because it is public, whereas age is not accessible because it is private. Nothing new there! But inside the Main class we then add the dynamic property gender, which traces out just fine. Using the keyword delete allows the removal of dynamic properties, which in turn, puts them up for garbage collection. In the Main class example, g.gender is deleted on line 14 and when a trace is performed on that property on line 15 you will see that it now outputs undefined as it is no longer available to the class.

I'm not entirely sure how practical a technique this is and I would suggest that properties and functions should always be defined inside the classes they are meant for, as it makes it slightly more difficult to see exactly what a program/class is doing. However, I think that if you don't plan on passing your code on to anyone else, it may be the quick 'escape' you need if you're too lazy to back into an imported class a defined the property. Just be warned though that classes that extend a dynamic class are not dynamic in themselves, so be prepared for some irritating error messages from time to time! :)

Most recent posts

  1. Flashcards Maker - the app the helps you learn in a flash
  2. Convert Font Suitcase to TTF in 3 Easy Steps
  3. Rain or Shine - Weather Forecast Available Now!
  4. Getting around Apple's silly rules for iOS 10
  5. Localising App Names for iOS and Android

Search site:

Apps by Ubacoda.com

Click the app icons to see more info


Archives

Categories