3.2 KiB
3.2 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7b8c367417b2b2512b54 | Use getters and setters to Control Access to an Object | 1 | 使用getter和setter来控制对象的访问 |
Description
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); //哇
Instructions
class
关键字创建Thermostat类。构造函数接受华氏温度。现在在类中创建getter
和setter
,以获得摄氏温度。请记住, C = 5/9 * (F - 32)
和F = C * 9.0 / 5 + 32
,其中F是华氏温标的温度值,C是摄氏温度相同温度的值注意当你实现这一点,你将在一个等级中跟踪班级内的温度 - 华氏温度或摄氏温度。这是getter或setter的强大功能 - 您正在为另一个用户创建一个API,无论您追踪哪个用户,都可以获得正确的结果。换句话说,您正在从使用者那里抽象出实现细节。 Tests
tests:
- text: <code>Thermostat</code>应该是一个<code>class</code>具有限定<code>constructor</code>方法。
testString: 'assert(typeof Thermostat === "function" && typeof Thermostat.constructor === "function","<code>Thermostat</code> should be a <code>class</code> with a defined <code>constructor</code> method.");'
- text: <code>class</code>关键字。
testString: 'getUserInput => assert(getUserInput("index").match(/class/g),"<code>class</code> keyword was used.");'
- text: <code>Thermostat</code>可以实例化。
testString: 'assert(() => {const t = new Thermostat(32); return typeof t === "object" && t.temperature === 0;}, "<code>Thermostat</code> can be instantiated.");'
Challenge Seed
function makeClass() {
"use strict";
/* Alter code below this line */
/* Alter code above this line */
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
Solution
// solution required