class Book {注意我们用来调用getter和setter的语法 - 就好像它们甚至不是函数一样。 Getter和setter很重要,因为它们隐藏了内部实现细节。
构造函数(作者){
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
const lol = new Book('anonymous');
的console.log(lol.writer); //匿名
lol.writer ='wut';
的console.log(lol.writer); //哇
class
关键字创建Thermostat类。构造函数接受华氏温度。现在在类中创建getter
和setter
,以获得摄氏温度。请记住, C = 5/9 * (F - 32)
和F = C * 9.0 / 5 + 32
,其中F是华氏温标的温度值,C是摄氏温度相同温度的值注意当你实现这一点,你将在一个等级中跟踪班级内的温度 - 华氏温度或摄氏温度。这是getter或setter的强大功能 - 您正在为另一个用户创建一个API,无论您追踪哪个用户,都可以获得正确的结果。换句话说,您正在从使用者那里抽象出实现细节。 Thermostat
应该是一个class
具有限定constructor
方法。
testString: 'assert(typeof Thermostat === "function" && typeof Thermostat.constructor === "function","Thermostat
should be a class
with a defined constructor
method.");'
- text: class
关键字。
testString: 'getUserInput => assert(getUserInput("index").match(/class/g),"class
keyword was used.");'
- text: Thermostat
可以实例化。
testString: 'assert(() => {const t = new Thermostat(32); return typeof t === "object" && t.temperature === 0;}, "Thermostat
can be instantiated.");'
```