Object-oriented programming practice discourages direct access to properties within a class. Classes typically define "getter" methods that provide read access and "setter" 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 would might define 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
; 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 "getter" method var name = obj.getUserName; // calling "setter" method obj.setUserName("Jody");
However, if you want to use a more concise syntax, use implicit getter and setter methods. Implicit getter/setter methods let you access class properties in a direct manner, but 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): { userName = name; }
A getter method must not take any parameters. A setter must take exactly one required parameter. A setter can have the same name as a getter in the same scope.
Unlike ordinary methods, getter and setter 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
using the getter and setter methods defined above.
var name = obj.user; obj.user = "Jack";
Note: Implicit getters and setters are syntactic shorthand for the Object.addProperty()
method in ActionScript 1 . See Adding getter/setter properties to objects.