freeCodeCamp “使用 getter 和 setter 来控制对象的访问“ 练习

引入

你可以从对象中获得一个值,也可以给对象的属性赋值。这些操作通常被称为 getters 以及 setters。Getter 函数的作用是可以让对象返回一个私有变量,而不需要直接去访问私有变量。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');
//分析
//注意这里的getter和setter名字都是writer
//第一次打印novel.writer时,没有传入参数,直接调用get writer(),返回this._author
//第二次打印时,传入了参数'newAuthor',先调用set writer()更新this._author的值,
//再直接调用get writer(),返回this._author
console.log(novel.writer);
novel.writer = 'newAuthor';
console.log(novel.writer);

控制台将显示字符串 anonymous 和 newAuthor

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

注意: 通常会在私有变量前添加下划线(_)。 然而,这种做法本身并不是将变量变成私有的。


练习

使用 class 关键字创建一个 Thermostat class。 constructor 接收一个华氏温度。

在 class 中,创建一个 getter 来获取摄氏温度和一个 setter 来设置温度值。

记得在 C = 5/9 * (F - 32) 和 F = C * 9.0 / 5 + 32 中,F 是华氏温度值,C 是摄氏温度值。

// 只修改这一行下面的代码
class Thermostat {
  constructor (temp) {
    this._temp=temp;
  }
  get temperature() {
    return 5/9*(this._temp-32);
  }
  set temperature(newTemp) {
    this._temp=newTemp*9/5+32;
  }
}
// 只修改这一行上面的代码

const thermos = new Thermostat(76); // 设置为华氏刻度
let temp = thermos.temperature; // 24.44 摄氏度
thermos.temperature = 26;
temp = thermos.temperature; // 26 摄氏度

分析:

  • 注意这里的getter和setter名字都是temperature

  • 第一次赋值给temp时,没有传入参数,直接调用get temperature(),返回this._temp

  • 第二次打印时,传入了参数'26'作为‘newTemp’,先调用set temperature()更新this._temp的值,再直接调用get temperature(),返回this._temp

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值