設定獲取功能

為了確保封裝,類的成員變數應該是 private,並且只能通過公共 get / set 訪問方法訪問 public。通常使用 _ 為私有欄位新增字首

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;
    }

有時你甚至不需要為 get / set 對建立一個 private 欄位。
例如,在像自定義無線電組這樣的控制元件中,你需要知道選擇了哪個單選按鈕,但是在課堂之外你只需要一個方法來 get / set 只有選中的值:

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;
        }
    }
}