Wednesday, February 6, 2013

Dynamic classes

A dynamic class defines an object that can be altered at runtime by adding or changing properties and methods. A class that is not dynamic, such as the String class, is a sealed class. You cannot add properties or methods to a sealed class at runtime. You create dynamic classes by using the dynamic attribute when you declare a class. For example, the following code creates a dynamic class named Protean.
dynamic class Protean {
     private var privateGreeting:String = "hi";
     public var publicGreeting:String = "hello";
     function Protean () {
          trace("Protean instance created");
     }
}
If you subsequently instantiate an instance of the Protean class, you can add properties or methods to it outside the class definition. For example, the following code creates an instance of the Protean class and adds a property named aString and a property named aNumber to the instance.
var myProtean:Protean = new Protean();
myProtean.aString = "testing";
myProtean.aNumber = 3;
trace (myProtean.aString, myProtean.aNumber); // Output: testing 3
Properties that you add to an instance of a dynamic Class are runtime entities, so any type checking is done at runtime. You cannot add a type annotation to property you add in this manner.
You can also add a method to the myProtean instance by defining a function and attaching the function to a property of the myProtean instance. The following code moves the trace statement into a method named traceProtean().
var myProtean:Protean = new Protean();
myProtean.aString = "testing";
myProtean.aNumber = 3;
myProtean.traceProtean = function () {
trace (myProtean.aString, myProtean.aNumber);
}
myProtean.traceProtean(); // Output: testing 3
Methods created in this way, however, do not have access to any private properties or methods of the Protean class. Moreover, even references to public properties or methods of the Protean class must be fully qualified. The following example shows the traceProtean() method attempting to access the private and public variables of the Protean class.
myProtean.traceProtean = function () {
     trace(myProtean.privateGreeting); // Output: undefined
     trace(myProtean.publicGreeting); // Output: hello
 }
myProtean.traceProtean();
Programming Actionscript 3. Powered by Blogger.