引入
你可以从对象中获得一个值,也可以给对象的属性赋值。这些操作通常被称为 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