巧用get和set,能夠直接操作物件屬性實現讀寫,可以極大的提高程式效率,給出一個典型範例:
var test = {
_Name : null,
_Age : 0,
//_Name的讀寫
set name(name) {this._Name = name;},
get name() {return this._Name;},
//_Age的讀寫
set age(age) {this._Age = age;},
get age() {return this._Age;}
}
alert(test.name " " test.age);//bull 0
test. name = 'lucy';
test.age = 20;
alert(test.name " " test.age);//lucy 20