Well, after a long break, part 2 of dynamic classes. If you want to refresh see Part 1
Continuing to that… read on:
At the time of writing this, subclasses of dynamic classes are not dynamic by default. Due to this, you may run into an ugly run-time error: Error #1056.
Imagine a sealed class, ClassSealed, that extends a dynamic class, ClassDynamic. If you create an object as ClassDynamic myObject = new ClassSealed(), an attempt to add a propery to myObject will produce a runtime error because the variable myObject points to a sealed object.
Try out.
Create a new action script class. Enter Check_Dynamic_Sealed as the class name. Punch in these lines of code:
package {
import flash.display.Sprite;
public class Check_Dynamic_Sealed extends Sprite
{
public function Check_Dynamic_Sealed()
{
}
}
}
Next, create a new class called ClassDynamic & punch in these lines of code:
package
{
public dynamic class ClassDynamic
{
public function ClassDynamic()
{
}
}
}
Now, instantiate and test the dynamic nature of the class ClassDynamic by adding the constructor in Check_Dynamic_Sealed class, like,
public function Check_Dynamic_Sealed()
{
var myClassDynamic:ClassDynamic = new ClassDynamic();
myClassDynamic.favoriteScripting = "ActionScript 3";
trace("Favorite Scripting = "+myClassDynamic.favoriteScripting);
}
Run this application in the debug mode, and sure enough it’ll print
Favorite Scripting = ActionScript 3, on the console output window.
Create one more sealed class called ClassSealed inherited from the dynamic ClassDynamic:
package
{
public class ClassSealed extends ClassDynamic
{
public function ClassSealed()
{
super();
}
}
}
Now, instantiate and test the Check_Dynamic_Sealed class using these lines of code:
public function AS_Only_Project()
{
var myClassSealed:ClassDynamic = new ClassSealed();
myClassSealed.favoriteScripting = "ActionScript 3";
trace("Favorite Scripting = "+myClassDynamic.favoriteScripting);
}
Good news is it compiles without any warnings or errors & the bad news is you will get an error saying,
ReferenceError: Error #1056: Cannot create property favoriteScripting on ClassSealed. at Check_Dynamic_Sealed()
Now even if you try to instantiate your sealed class as follows:
var myClassSealed:ClassDynamic = new ClassSealed() as ClassDynamic;
the same error occurs.
Quoting the words of Yakov Fain, “If you need to add new functionality to one of the existing standard Flex components (buttons, comboboxes and the like), do not bother extending them and creating new classes. Just create one simple empty subclass with the keyword dynamic and instantiate and add new properties on the fly as needed.”
[...] This is how a dynamic class is used in AS3. Part 2 [...]
Useful blog.