ES6基礎之——get 與 set

在類裏面能夠去定義一些getter和setter,getter能夠獲得一些東西的方法,setter能夠設置東西
class Chef{
  constructor(food){
    this.food = food;
    thid.dish = [];
  }

  //getter
  get menu(){
    return this.dish
  }

  //setter
  set menu(dish){
    this.dish.push(dish)
  }

  cook(){
    console.log(this.food)
  }
}

let zhangsan =new Chef();
console.log(zhangsan.menu = 'tomato' ); //tomato
console.log(zhangsan.menu = 'pizza' ); //pizza
console.log(zhangsan.menu); //["tomato","pizza"]
相關文章
相關標籤/搜索