ES6_使用getter和setter控制对对象的访问

Getter函数旨在简单地向用户返回(获取)对象私有变量的值,而无需用户直接访问私有变量。

Setter函数用于根据传递给Setter函数的值修改(设置)对象私有变量的值。此更改可能涉及计算,甚至完全覆盖以前的值。

class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const novel = new Book('anonymous');
console.log(novel.writer); //anonymous
novel.writer = 'newAuthor';
console.log(novel.writer); //newAuthor

请看用于调用getter和setter的语法。它们看起来甚至不像函数。getter和setter很重要,因为它们隐藏了内部实现细节。

注:按照惯例,在私有变量名称前加下划线‘_’。然而,上面例子本身并不使变量私有。

下面的例子将输入的华氏度转换为摄氏度展示给用户:

class Thermostat {
  constructor(fahrenheit ){
    this.fahrenheit =fahrenheit;//构造函数接受华氏温度。
  }
  get temperature(){
    return  5/9 * (this.fahrenheit - 32);//将身为华氏度的构造函数的私有变量转换成摄氏度输出给用户。
  }
  set temperature(data){
    this.fahrenheit=data * 9.0 / 5 + 32;//将输入的新数据转变成华氏度值传给构造函数的私有变量。
  }
}
const thermos = new Thermostat(76); // 以华氏温标设置
let temp = thermos.temperature; // 24.44摄氏度(Celsius)
console.log(temp); //24.444444444444446
thermos.temperature = 26;
temp = thermos.temperature; // 26摄氏度(Celsius)
console.log(temp); //26

 

posted @ 2022-09-15 17:36  枭二熊  阅读(98)  评论(0编辑  收藏  举报