EasyManua.ls Logo

MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT - Creating Dynamic Classes

MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT
816 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Creating dynamic classes 173
As you can see, getUserName returns the current value of userName, and setUserName sets the
value of
userName to the string parameter passed to the method. An instance of the class would
then use the following syntax to get or set the
userName property.
// calling "get" method
var name = obj.getUserName();
// calling "set" method
obj.setUserName("Jody");
However, if you want to use a more concise syntax, use implicit get/set methods. Implicit get/set
methods let you access class properties in a direct manner, while maintaining good OOP practice.
To define these methods, use the
get and set method attributes. You create methods that get or
set the value of a property, and add the keyword
get or set before the method name.
function get user():String {
return userName;
}
function set user(name:String):Void {
userName = name;
}
A get method must not take any parameters. A set method must take exactly one required
parameter. A set method can have the same name as a get method in the same scope. Get/set
methods cannot have the same name as other properties. For example, in the example code above
that defines get and set methods named
user, you could not also have a property named user in
the same class.
Unlike ordinary methods, get/set methods are invoked without any parentheses or arguments. For
example, the following syntax could now be used to access or modify the value of
userName with
the get/set methods defined above.
var name = obj.user;
obj.user = "Jack";
Note: Implicit get/set methods are syntactic shorthand for the Object.addProperty() method
in ActionScript 1.
Creating dynamic classes
By default, the properties and methods of a class are fixed. That is, an instance of a class cant
create or access properties or methods that werent originally declared or defined by the class. For
example, consider a Person class that defines two properties,
name and age:
class Person {
var name:String;
var age:Number;
}
If, in another script, you create an instance of the Person class and try to access a property of the
class that doesnt exist, the compiler generates an error. For example, the following code creates a
new instance of the Person class (
a_person) and then tries to assign a value to a property named
hairColor, which doesnt exist.
var a_person:Person = new Person();
a_person.hairColor = "blue"; // compiler error
This code causes a compiler error because the Person class doesnt declare a property named
hairColor. In most cases, this is exactly what you want to happen.

Table of Contents

Related product manuals