AS2 OOP: Class Structure
         by senocular  

Get and Set
Get and set are new keywords in ActionScript 2.0 that help you manage your private variables. They take the place of ActionScript 1.0's addProperty method. Whereas addProperty handled both get and set methods within a single method call, get and set handle each separately in the definition of the setting or getting function.

The get and set keywords are kind of used like static and private. They appear in the definition of the function they're being used on. Only here, get and set are placed after the function keyword. This puts them right before the name of the get or set property being created making it more verbose when reading the script. Here's an example that makes a name property for a class that sets and retrieves a username private property. The name of the get or set method determines the name of the property they're creating.

// in Account.as
class Account {
private var currentOwner:String = "none";
 
function Account(name:String){
currentOwner = name;
}
 
function get owner():String {
return currentOwner;
}
function set owner(name:String):Void {
currentOwner = name;
}
}
// in Flash movie
var myChecking:Account = new Account("Terry");
trace(myChecking.owner); // Terry
 
myChecking.owner = "Terry's son";
trace(myChecking.owner); // Terry's son

Being a private property, currentOwner is not directly accessible from an Account instance. Using the get and set methods, an owner property was created to access it. This property is a result of the combinations of get owner() and set owner() - two methods for handling the currentOwner property. Here is the ActionScript 1.0 equivalent of the above.

/* ActionScript 1.0 */
Account = function(name){
this.currentOwner = name;
}
getOwner = function(){
return this.currentOwner;
}
setOwner = function(name){
this.currentOwner = name;
}
Account.prototype.addProperty("owner", getOwner, setOwner);

In ActionScript 2.0 both get and set methods can have, but are not limited to, the same name. After all, this is generally needed for the getting and setting of the variable they create. They cannot, however, have the same name as other properties and methods within the class. Also, it is not required that there be both a set and get for any one property created in this manner. A set can be created without a get and vise versa.

Using get and set in this manner may seem like a futile process, but its good OO programming practice not to allow direct access to your properties from your instances.

 

 




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.