Dynamic classes

A dynamic class defines an object that can be altered at run time 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 run time.

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); // testing 3

Properties that you add to an instance of a dynamic class are run-time entities, so any type checking is done at run time. You cannot add a type annotation to a property that 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(this.aString, this.aNumber); 
}; 
myProtean.traceProtean(); // 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 qualified with either the this keyword or the class name. 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); // undefined 
    trace(myProtean.publicGreeting); // hello 
}; 
myProtean.traceProtean();