Skip to the workspace
Pebellslearn by building
Classes  ›  Lesson

Getters, Setters and Static Members

Classes 12 min

javascript / Getters, Setters and Static Members

Explore each scene at your own pace.

01 · Getters, Setters and Static Members

Getters, Setters and Static Members

Getters, Setters and Static Members

Getters run code when a property is read; setters run code when it is assigned. Static members belong to the class constructor rather than individual instances.

A property-like interface may compute or validate instead of directly exposing a stored field.

See the mechanism

Walk through the modelGetters, Setters and Static MembersAuthored snapshots of the example; use Run below to test the code.
minutes4
seconds getter240
The getter computes rather than storing another independent number.
1 of 3

Follow one example

javascript

The assignment invokes the setter and stores 5 minutes. Reading seconds invokes the getter and computes 300. unit is called on ReadingTime, not on time. Avoid a setter that assigns back to the same accessor name indefinitely; use a separate backing field or another property.

Predict, change and check

Predict: Does time.seconds() call a getter correctly, or does property access already invoke it?

Test your explanation: Compare time.seconds with time.seconds(). Add validation to the setter so negative time cannot be stored silently.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Accessors and static members have different receivers

A getter can compute a property read and a setter can validate a property write. They may run code even though the call site looks like simple field access. Store validated backing state under a different field so a setter does not recursively assign to itself.

A static method belongs to the class constructor object, not to every instance's normal method interface. It can be useful for a named factory or a class-level operation. It does not automatically receive a particular instance as this. Test read/write behavior separately from class-level construction behavior.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.