Extending classes at runtime

By default, the properties and methods of a class are fixed. That is, an instance of the class can't create or access properties or methods that weren't originally declared or defined by the class. Consider the Person class again that was used in Using classes: a simple example. Remember that the class defines two properties: name and age.

class Person {
	var name:String;
	var age:Number;
}

If, in another script, we create an instance of the Person class and try to access a property of the class that doesn't exist, the compiler will generate an error. Consider the following code as an example. It creates a new instance of the Person class (a_person) and then tries to assign a value to a property named hairColor, which doesn't exist.

var a_person:Person = new Person();
a_person.hairColor = "blue"; // compiler error

This code causes a compiler error because the Person class doesn't declare a property named hairColor. In most cases, this is exactly what you want to happen. For instance, you might mistype the name of a property that does, in fact, belong to a class. As a result, your application doesn't work as expected and you waste time trying to figure out why. By catching the problem during compilation you've saved yourself all that debugging time.

But, in some cases, you might want to be able to add or access properties of methods of a class at runtime—that is, dynamically. The dynamic class modifier lets you do just that. For example, if in the previous example, we added the dynamic modifier to the Person class, as shown below.

dynamic class Person {
	var name:String;
	var age:Number;
}

Now, instances of the Person class can add and access properties and methods that aren't defined in the original class.

var a_person = new Person();
a_person.hairColor = "blue";
a_person.eatLunch = function () {
	

The dynamic modifier is especially useful when extending the MovieClip class.