【JavaScript】getter / setter

getter跟setter都是寫在物件底下的function方法

getter

給物件綁定訪問時(Access)可取得的函數

var obj = {
 log: ['example','test'],
 get latest() {
 if (this.log.length == 0) {
   return undefined;
  }else{
   return this.log[this.log.length - 1];
  }
 }
}

console.log(obj.log); //['example', 'test']
console.log(obj.latest); // "test"

setter

setter可以設定參數,然後讓物件回傳不同的值

//language 是一個物件
var language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN'; //透過setter設定參數
console.log(language.log); // ['EN']

language.current = 'FA'; //透過setter設定參數
console.log(language.log); // ['EN', 'FA']