GGistDev

Classes in JavaScript

Classes provide syntactic sugar over prototypes for defining constructor functions, fields, and methods.

Defining a class

class User {
  constructor(name) {
    this.name = name
  }
  greet() { return `Hi ${this.name}` }
}

Fields and private members

Public and private fields (stage‑4, widely supported).

class Counter {
  #n = 0         // private field
  static ZERO = 0
  inc() { this.#n++ }
  value() { return this.#n }
}

Inheritance and super

class Admin extends User {
  greet() { return `[ADMIN] ` + super.greet() }
}

Static methods and properties

class MathUtil {
  static add(a, b) { return a + b }
}
MathUtil.add(1,2)

Getters and setters

class Point {
  constructor(x, y) { this.x = x; this.y = y }
  get length() { return Math.hypot(this.x, this.y) }
  set length(v) { const a = Math.atan2(this.y, this.x); this.x = v*Math.cos(a); this.y = v*Math.sin(a) }
}

Mixins (pattern)

Compose behavior by copying prototypes or returning subclassing functions.

this semantics

Within class methods, this is the instance; when extracting methods, bind if used as callbacks.

Summary

  • Use class fields (public/private), static, and accessors for clarity
  • Extend with extends/super; consider composition/mixins for cross‑cutting behavior