If you’ve created an object from a particular class, you can use only properties and methods that were defined in this class. For example,
class Example{
String variable_name;
}
You can only manipulate with the variable_name property, like,
Example ex = new Example();
ex.variable_name = “This is a String”;
And for the purpose of tracing/printing-out output etc, you use ex.variable_name.
ActionScript calls such classes sealed, but with the help of dynamic classes, we can programmatically add new properties and behavior to classes during the run-time. Just add the keyword dynamic to the class definition, like,
dynamic class Example {
var variable_name:String;
}
Now let’s add dynamically one variable new_variable and the function newFunction() to the object of type Example, like,
Example ex = new Example();
ex.variable_name = "This is a String";
ex.age = 30;
ex.newFunction = function () {
trace (ex.variable_name, ex.age);
}
ex.newFunction(); //outputs -> This is a String 30
Do remember that you do not have complete freedom though, you can dynamically add only public properties and methods. Of course, nothing comes for free and sealed classes are a bit more efficient in terms of memory consumption, because they do not need to create a hash table to store the properties and methods that are unknown during compilation. Another obvious restriction is that dynamically added functions can’t access private members of the dynamic class.
In AS3, any function can be attached to a dynamically created property of a dynamic object, for example
function someFunction():Number {…}
var myObject:SomeObject = new SomeObject();
myObject.calc = someFunction; //add the calc property and attach the function someFunction()
var myVar = myObject.someFunction();
The delete operator destroys the property of an object and makes it eligible for garbage collection:
delete someFunction(); myVar = myObject.someFunction() // generates an error
Some of the Flex classes were defined as dynamic, i.e. Object, Array, MovieClip, NetConnection, TextField, and others.
This is how a dynamic class is used in AS3. Part 2
courtesy: http://flexblog.faratasystems.com/
[...] « ActionScript 3: Dynamic Classes [...]
[...] Now, that piece of code is extensible, right? Wondering what is dynamic classes? Look here. [...]