freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../es6/use-getters-and-setters-to-...

3.2 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b8c367417b2b2512b54 Use getters and setters to Control Access to an Object 1 使用getter和setter来控制对象的访问

Description

您可以从对象获取值,并在对象中设置属性的值。这些通常被称为gettersetter 。 Getter函数旨在简单地将对象的私有变量的值返回获取给用户而无需用户直接访问私有变量。 Setter函数用于根据传递给setter函数的值修改设置对象私有变量的值。此更改可能涉及计算甚至完全覆盖先前的值。
class Book {
构造函数(作者){
this._author = author;
}
// getter
get writer{
return this._author;
}
// setter
set writerupdatedAuthor{
this._author = updatedAuthor;
}
}
const lol = new Book'anonymous';
的console.loglol.writer; //匿名
lol.writer ='wut';
的console.loglol.writer; //哇
注意我们用来调用getter和setter的语法 - 就好像它们甚至不是函数一样。 Getter和setter很重要因为它们隐藏了内部实现细节。

Instructions

使用class关键字创建Thermostat类。构造函数接受华氏温度。现在在类中创建gettersetter ,以获得摄氏温度。请记住, 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