← JavaScript

Intermediate · 7 of 17 · 17 min read

Classes

What class is syntax for, where the methods actually live, and the fields, getters, statics and private names worth knowing.

  • Classes

A class is a template for objects. The syntax arrived in ES2015 and is mostly a tidier spelling of the constructor-function and prototype pattern that came before it — but “mostly” hides a few real differences, and those are what gets asked.

The shape

class User {
  // a field: created fresh on every instance
  role = 'member';

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // a method: created once, on User.prototype
  greet() {
    return `Hi, I am ${this.name}`;
  }
}

const ana = new User('Ana', 30);
console.log(ana.greet());  // "Hi, I am Ana"
console.log(ana.role);     // "member"

The class is the blueprint and the instances are the objects — one definition, any number of objects with the same abilities and their own data:

const beto = new User('Beto', 25);
console.log(ana.name, beto.name);           // Ana Beto — separate data
console.log(ana.greet === beto.greet);      // true — one shared function
console.log(Object.hasOwn(ana, 'greet'));   // false — it is on the prototype
console.log(Object.hasOwn(ana, 'role'));    // true  — fields are own properties

Where everything lives

class User {
  role = 'member';
  constructor(name) { this.name = name; }
  greet() { return this.name; }
  static version = '1.0';
  static create(name) { return new User(name); }
}

const u = new User('Ana');

console.log(Object.keys(u));                       // ["role", "name"] — own
console.log(Object.getOwnPropertyNames(User.prototype)); // ["constructor", "greet"]
console.log(Object.getPrototypeOf(u) === User.prototype); // true
console.log(User.version);                          // "1.0" — on the class itself
console.log(u.version);                             // undefined — not inherited by instances
Declared as Lives on One copy or many
method() {} Class.prototype one, shared
field = value the instance one per instance
method = () => {} the instance one per instance
static x / static m() {} the class one
#secret the instance, truly private one per instance

The practical consequence of row three: an arrow field fixes this but costs a function object per instance.

It is sugar — with teeth

The equivalent pre-class code, so the sugar is visible:

function OldUser(name) {
  this.name = name;
}
OldUser.prototype.greet = function () {
  return `Hi, I am ${this.name}`;
};

console.log(new OldUser('Ana').greet()); // "Hi, I am Ana"
console.log(typeof class {});            // "function" — a class *is* a function

But a class is not interchangeable with that function. The differences that matter:

class Modern {}
function Legacy() {}

// 1. A class cannot be called without `new`:
// Modern();            // TypeError: Class constructor cannot be invoked without 'new'
console.log(Legacy());  // undefined — happily called, and `this` is wrong

// 2. Class bodies are always strict mode, whatever the surrounding file.

// 3. Class declarations are not hoisted-with-value — they sit in the TDZ:
// new Later();         // ReferenceError: Cannot access 'Later' before initialization
class Later {}

// 4. Class methods are non-enumerable:
class WithMethod { m() {} }
console.log(Object.keys(WithMethod.prototype)); // [] — a for...in will not list it

Getters and setters

A pair of functions that read like a property. Useful for a derived value, or for validating on write:

class Rect {
  constructor(w, h) {
    this.w = w;
    this.h = h;
  }

  get area() {
    return this.w * this.h; // computed on every read
  }

  set width(value) {
    if (value <= 0) throw new RangeError('width must be positive');
    this.w = value;
  }
}

const r = new Rect(3, 4);
console.log(r.area); // 12 — no parentheses
r.width = 10;
console.log(r.area); // 40
// r.area = 5;       // TypeError in strict mode: no setter

A getter with no setter is a read-only property, which is often exactly what you want for something derived.

Static members

Attached to the class, not to instances. The natural home for factories, constants and helpers that do not need an instance:

class Temperature {
  static ABSOLUTE_ZERO = -273.15;

  constructor(celsius) { this.celsius = celsius; }

  static fromFahrenheit(f) {
    return new Temperature((f - 32) / 1.8);
  }

  static isValid(celsius) {
    return celsius >= Temperature.ABSOLUTE_ZERO;
  }
}

console.log(Temperature.fromFahrenheit(212).celsius); // 100
console.log(Temperature.isValid(-300));               // false
console.log(Temperature.ABSOLUTE_ZERO);               // -273.15

Inside a static method, this is the class, which is what makes a static factory inheritable:

class Base {
  static create() { return new this(); } // `this` is whichever class was used
}
class Derived extends Base {}

console.log(Derived.create() instanceof Derived); // true

Private fields

A # name is private at the language level — not a convention, not enumerable, not reachable from outside:

class Account {
  #balance = 0;

  deposit(amount) {
    if (amount <= 0) throw new RangeError('amount must be positive');
    this.#balance += amount;
    return this;
  }

  get balance() {
    return this.#balance; // read-only from outside
  }

  static isAccount(value) {
    return #balance in value; // the ergonomic brand check
  }
}

const acc = new Account();
acc.deposit(100);
console.log(acc.balance);            // 100
console.log(Object.keys(acc));       // [] — invisible
console.log(JSON.stringify(acc));    // {} — not serialised
// acc.#balance;                     // SyntaxError, at parse time
console.log(Account.isAccount(acc), Account.isAccount({})); // true false

The older _balance convention still appears everywhere; the difference is that _balance is only a request, and #balance is enforced. Note that # names are not serialised by JSON.stringify, so a class with private state needs its own toJSON if it has to travel.

this in a class method

Class methods are plain functions on the prototype, so they lose their receiver like any other method:

class Counter {
  count = 0;
  increment() { this.count += 1; return this.count; }
  incrementSafe = () => { this.count += 1; return this.count; };
}

const c = new Counter();
const loose = c.increment;
// loose();                  // TypeError: Cannot read properties of undefined
console.log(c.increment());  // 1 — called through the instance
const safe = c.incrementSafe;
console.log(safe());         // 2 — the field arrow captured `this`

Three fixes, in order of preference: call it through the instance; pass an arrow that calls it; or make it a field arrow when it is always used detached — accepting the per-instance cost.

Common mistakes

Putting shared data in a field

Mistake. class Store { items = [] } and then treating items as shared state. Why it fails. Each instance gets its own array, so nothing is shared — and the mirror mistake, putting the array on the prototype, shares it between all instances. What to do instead. Per-instance data in a field; shared data as a static on the class.

class Bad { static items = []; }   // genuinely shared — and usually a bug magnet
class Good { items = []; }         // one array per instance
new Good().items.push(1);
console.log(new Good().items);     // [] — unaffected

Forgetting new

Mistake. const u = User('Ana'). Why it fails. A class constructor throws a TypeError when called without new — which is better than the pre-class version, where it silently wrote onto the global object. What to do instead. new User('Ana'), or add a static create() factory if a bare call should be allowed.

Assuming a getter is cheap

Mistake. A getter that filters a large array, read inside a loop. Why it fails. It looks like a property but runs its body on every access, so an O(n) getter read n times is O(n²). What to do instead. Keep getters trivial, or compute once into a local variable before the loop.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

Class methods have to live somewhere, and it is not on each instance.

What does this log?

Code sample
class A {
  method() {}
}

const a = new A();
console.log(Object.keys(a).length);

In a subclass constructor, this does not exist from the first line.

What happens when this runs?

Code sample
class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor(name) {
    this.breed = "lab";
    super(name);
  }
}

new Dog("Rex");

What does a static member belong to?

Practise Classes →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.