Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.5 — Classes
JavaScript · Example 5 of 5

An arrow-function field keeps this for event handlers

The arrow is created per instance (a field), so its this is that instance. The cost: each instance has its own copy instead of one shared prototype method.

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.

01

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.

02

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.

03

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

01

What does the class syntax actually create? Is it only syntax sugar?

02

Where do constructor properties, fields, methods, getters and static members end up?

03

When would you use a static method instead of an instance method?

04

Why might you write a method as an arrow-function field, and what does it cost?

An arrow-function field keeps this for event handlers

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

on: true
on: false
own copy per instance? true