设置获取功能
为了确保封装,类的成员变量应该是 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;
}
}
}