ActionScript 3 Object Oriented Programming set & get functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

To ensure encapsulation, member variables of a class should be private and only be accessible to public via public get/set access methods. It is a common practice to prefix private fields with _

public class Person
{
    private var _name:String = "";

    public function get name():String{
        return _name;
        //or return some other value depending on the inner logic of the class
    }


    public function set name(value:String):void{
        //here you may check if the new value is valid
        //or maybe dispatch some update events or whatever else
        _name = value;
    }

Sometimes you don't even need to create a private field for a get/set pair.
For example in a control like a custom radio group you need to know which radio button is selected, however outside the class you need just a way to get/set only the selected value:

public function get selectedValue():String {
    //just the data from the element
    return _selected ? _selected.data : null;
}
public function set selectedValue(value:String):void {
    //find the element with that data
    for (var i:int = 0; i < _elems.length; i++) {
        if (_elems[i].data == value) {
            _selected = _elems[i];//set it 
            processRadio();//redraw
            return;
        }
    }
}


Got any ActionScript 3 Question?