260 Classes
6. Add the following code to create a new instance of the Person class (firstPerson), and try
to assign a value to a property called
hairColor (which doesn’t exist in the Person class):
var firstPerson:Person = new Person();
firstPerson.hairColor = "blue"; // Error. There is no property with the
name 'hairColor'.
7.
Save the Flash document.
8. Select Control > Test Movie to test the code.
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. Compiler
errors might not seem desirable, but they are very beneficial to programmers: good
error messages help you to write correct code by pointing out mistakes early in the
coding process.
In some cases, however, you might want to add and access properties or methods of a class at
runtime that aren’t defined in the original class definition. The dynamic class modifier lets
you do just that.
To create a dynamic class:
1. Select File > New and then select ActionScript File, and then click OK.
2. Select File > Save As and name the file Person2.as. Save the file on your hard disk.
3. Type the following code into the Script window:
dynamic class Person2 {
public var userName:String;
public var age:Number;
}
This ActionScript adds the dynamic keyword to the Person class in the previous example.
Instances of the Person2 class can add and access properties and methods that are not
defined in this class.
4. Save your changes to the ActionScript file.
5. Select File > New and then select Flash Document to create a new FLA file, and then
click OK.
6. Select File > Save As and name the new file person2_test.fla. Save it in the same directory
as Person2.as.
7. Type the following code to create a new instance of the Person2 class (firstPerson), and
assign a value to a property called
hairColor (which doesn’t exist in the Person2 class).
var firstPerson:Person2 = new Person2();
firstPerson.hairColor = "blue";
trace(firstPerson.hairColor); // blue