Skip to the workspace
Pebellslearn by building
Classes  ›  Lesson

Class Syntax and Constructors

Classes 12 min

javascript / Class Syntax and Constructors

Explore each scene at your own pace.

01 · Class Syntax and Constructors

Class Syntax and Constructors

Class Syntax and Constructors

A class defines instance construction and shared methods. new creates an instance and runs its constructor with that instance as this.

The constructor initializes each article; methods describe behavior shared by its instances.

See the mechanism

Walk through the modelClass Syntax and ConstructorsAuthored snapshots of the example; use Run below to test the code.
instance A.title"Morning"
A.savedfalse
The constructor initializes this new instance.
1 of 3

Follow one example

javascript

The constructor initializes fields on the new instance. save is normally stored on the class prototype and called with the instance receiver. Creating a second Article makes separate fields; saving one does not automatically save the other. Classes are built on JavaScript’s prototype model and must be constructed with new.

Predict, change and check

Predict: If you construct two articles and save only the first, which saved flags change?

Test your explanation: Create the second instance and check both flags. Move a field initialization out of the constructor only after deciding whether it should belong to each instance or a shared object.

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

Apply and distinguish

Construct an instance with an explicit invariant

A class constructor initializes a new instance, and ordinary instance methods are shared through the class's prototype. Methods do not become copies inside each instance merely because class syntax looks like one block. Class bodies use strict semantics.

Validate the conditions that an instance must maintain, then route changes through operations that preserve them. A class is not a universal requirement for every record: a plain object and functions can be simpler when no instance behavior or invariant is needed. Test two instances to verify that instance state is not accidentally global.

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.