ES6—get 与 set

在类里面可以去定义一些getter和setter,getter可以得到一些东西的方法,setter可以设置东西

class Chef{
  constructor(food){
    this.food = food;
    this.dish = [];
  }
 
  //getter
  get menu(){
    return this.dish
  }
 
  //setter
  set menu(dish){
    this.dish.push(dish)
  }
 
  cook(){
    console.log(this.food)
  }
}
 
let xiaoming=new Chef();
console.log(xiaoming.menu = 'tomato' ); //tomato 
console.log(xiaoming.menu = 'pizza' ); //pizza
console.log(xiaoming.menu); //["tomato","pizza"]

  

原文地址:https://www.cnblogs.com/ympjsc/p/12304818.html