![]() ![]() ![]() | |
![]() | |
![]() | |
![]() |
The next step is to create an instance of the Person class in another script, such as a frame script in a Flash (FLA) document or another AS script, and assign it to a variable. To create an instance of a custom class, you use the new
operator, just as you would when creating an instance of a built-in ActionScript class (such as the XML or TextField class).
For example, the following code creates an instance of the Person class and assigns it to the variable newPerson
.
var newPerson:Person = new Person("Nate", 32);
This code invokes the Person class's constructor function, passing as parameters the values "Nate" and 32.
The newPerson
variable is typed as a Person object. Typing your objects in this way enables the compiler to ensure that you don't try to access properties or methods that aren't defined in the class. (The exception is if you declare the class to be dynamic using the dynamic
keyword. See Creating dynamic classes.)
var person_1:Person = new Person("Nate", 32); var person_2:Person = new Person("Jane", 28); trace(person_1.showInfo()); trace(person_2.showInfo());
The above code creates two instances of the Person class, person_1
and person_2
, and then calls the showInfo()
method on each instance.
Hello, my name is Nate and I'm 32 years old. Hello, my name is Jane and I'm 28 years old.
When you create an instance of a class by calling its constructor function, Flash looks for an ActionScript file of the same name as the constructor in a set of predetermined directory locations. This group of directory locations is known collectively as the classpath (see Understanding the classpath).
You should now have an overall idea of how to create and use classes in your Flash documents. The rest of this chapter explores classes and interfaces in more detail.
![]() | |
![]() | |
![]() | |
![]() ![]() ![]() |