Command Palette

Search for a command to run...

Hectal
Phase 7: this, Prototypes and Classes
JavaScript · Exercise 3 of 5 PreviousNext
Intermediate

A Temperature class with a getter, setter and factory

Write a class Temperature that stores one value, celsius, set from the constructor.

Add a getter fahrenheit (celsius × 9 / 5 + 32) and a setter fahrenheit that converts back to Celsius. The setter must throw a TypeError if it gets something that isn't a number.

Add a static method fromFahrenheit(f) that returns a new Temperature.

Finally, wire up the page: typing a Celsius value into #celsius shows the Fahrenheit value in #fahrenheit, using your class.

What Check tests

  1. new Temperature(25).fahrenheit is 77
  2. Setting fahrenheit = 212 makes celsius 100
  3. The setter throws a TypeError for a non-number
  4. Temperature.fromFahrenheit(32) returns a Temperature at 0 °C
  5. Typing 100 in the Celsius box shows 212
  6. Temperature is written as a class

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.