JavaScript - Classes & Static Methods
Overview
Estimated time: 35–45 minutes
Classes provide a declarative syntax for prototype-based inheritance. Add instance methods, static methods, and fields (including private #
fields).
Learning Objectives
- Define classes with constructors, instance methods, and static methods.
- Use public fields and private
#
fields. - Understand that classes are not hoisted like function declarations.
Prerequisites
Class basics
class Counter {
#count = 0; // private field
constructor(start = 0){ this.#count = start; }
inc(){ this.#count++; }
get value(){ return this.#count; } // accessor
static from(counter){ // static factory
const c = new Counter();
c.#count = counter.value;
return c;
}
}
const c = new Counter(1); c.inc(); c.value; // 2
Common Pitfalls
- Classes are not hoisted for usage before declaration; define before use.
- Private
#
fields are truly private; they cannot be accessed via bracket syntax.