dynamic class Protean {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.
private var privateGreeting:String = "hi";
public var publicGreeting:String = "hello";
function Protean () {
trace("Protean instance created");
}
}
var myProtean:Protean = new Protean();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.
myProtean.aString = "testing";
myProtean.aNumber = 3;
trace (myProtean.aString, myProtean.aNumber); // Output: testing 3
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();