[FLEX] What is dynamic keyword used for? or What is the difference between sealed class and dynamic classes?

Dynamic Keyword is used to make a class dynamic. A dynamic class defines an object that can be altered at run time by adding or changing properties and methods. We create dynamic classes by using the dynamic attribute when we 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 we subsequently instantiate an instance of the Protean class, we 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 we add to an instance of a dynamic class are run-time entities, so any type checking is done at run time. We cannot add a type annotation to a property that we add in this manner.
We 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(); // 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 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); // output: undefined
trace(myProtean.publicGreeting); // output: hello
}
myProtean.traceProtean();

dynamically added or redefined functions can’t access private members of the dynamic
class
Sealed Class
A class that is not dynamic, such as the String class, is a sealed class. We cannot add properties or methods to a sealed class at run time.

Comments

Popular posts from this blog

[SVN] Simple way to do code review

How to Choose a Technology Stack for Web Application Development

Setting ESLint on a React Typescript project