Getters, setters and a static factory
Only celsius is stored. fahrenheit is computed by the getter and converted back by the setter, which also checks the value.
A class is a cleaner way to write a constructor and its prototype methods in one block, with fields, static members, getters and setters; under the hood it builds the same prototype chain, but adds safety rules such as strict mode and refusing to run without new.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Rectangle with width and height from the constructor, a getter area, a method scale(factor) that returns a new Rectangle, and a static square(size). Print new Rectangle(2, 3).area and Rectangle.square(4).scale(2).area.
Write a class Ticket that gives every new ticket an id from a static counter (1, 2, 3, ...). Create three tickets and print their ids.
Write a class Username with a setter value that trims the text and throws a RangeError if it's shorter than 3 characters, and a getter that returns it. Show a valid and an invalid assignment.
Explain it without notes
What does the class syntax actually create? Is it only syntax sugar?
Where do constructor properties, fields, methods, getters and static members end up?
When would you use a static method instead of an instance method?
Why might you write a method as an arrow-function field, and what does it cost?
Preview
Console
Nothing logged yet.Expected console output
77
100 Temperature { celsius: 100 }
Temperature { celsius: 0 }
TypeError: fahrenheit must be a number