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"]

  

posted @ 2019-07-03 08:38  qnlz  阅读(9261)  评论(0编辑  收藏  举报