Classes, the modern parts in JavaScript
Field declarations, private members, static blocks and accessors.
class Session {
#runs = [];
static created = 0;
static {
Session.created = 0;
}
constructor(lang) {
this.lang = lang;
Session.created += 1;
}
record(tpm) {
this.#runs.push(tpm);
return this;
}
get best() {
return this.#runs.length ? Math.max(...this.#runs) : 0;
}
static from(lang, ...runs) {
const session = new Session(lang);
runs.forEach((tpm) => session.record(tpm));
return session;
}
}
const session = Session.from("go", 98, 104);
console.log(session.best, Session.created, Object.keys(session));
How it works
- A
#namefield is genuinely private: no reflection reaches it. - Class fields replace assigning in the constructor.
staticmembers and blocks belong to the class itself.
Keywords and builtins used here
MathObjectclassconstconstructorfromreturnstaticthis
The run, in numbers
- Lines
- 31
- Characters to type
- 508
- Tokens
- 156
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 99 seconds.
Step 2 of 3 in Classes, step 36 of 43 in Language basics.