![]() ![]() ![]() | |
![]() | |
![]() | |
![]() |
Object-oriented programming practice discourages direct access to properties within a class. Classes typically define "get" methods that provide read access and "set" methods that provide write access to a given property. For example, imagine a class that contains a property called userName
:
var userName:String;
Instead of allowing instances of the class to directly access this property (obj.userName = "Jody"
, for example), the class might have two methods, getUserName
and setUserName
, that would be implemented as follows:
function getUserName:String() { return userName; } function setUserName(name:String): { userName = name; }
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.
![]() | |
![]() | |
![]() | |
![]() ![]() ![]() |