TExcelTAD
Home › JavaScript › JS Classes

JavaScript Classes

A class is a blueprint for creating objects that share the same structure and behaviour. Where an object literal creates one object, a class lets you stamp out as many similar objects (called instances) as you need — users, products, enemies in a game — each with its own data but the same methods.

Defining a class

js · try it yourself
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  priceWithTax(rate = 0.2) {
    return +(this.price * (1 + rate)).toFixed(2);
  }

  describe() {
    return `${this.name} costs ${this.price.toFixed(2)} €`;
  }
}

const lamp = new Product("Lamp", 39.9);
const desk = new Product("Desk", 220);

console.log(lamp.describe());
console.log(desk.priceWithTax());
console.log(lamp);
console.log(lamp instanceof Product, typeof Product);
Lamp costs 39.90 €
264
Product { name: 'Lamp', price: 39.9 }
true function
  • constructor runs automatically when you call new Product(…). It sets up the instance's properties via this.
  • Methods (describe, priceWithTax) are shared by all instances.
  • Class names use PascalCase by convention.
  • A class must be called with new; calling Product() directly throws a TypeError.

Class fields, private fields and static members

You can declare properties directly in the class body (fields). Names starting with # are private — only code inside the class can read or change them. static members belong to the class itself rather than to instances:

js · try it yourself
class BankAccount {
  static #nextId = 1;
  static bankName = "JS Bank";

  id = BankAccount.#nextId++;
  #balance = 0;              // private
  transactions = [];

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

  deposit(amount) {
    if (amount <= 0) throw new RangeError("Deposit must be positive");
    this.#balance += amount;
    this.transactions.push(`+${amount}`);
    return this;             // allows chaining
  }

  get balance() {            // a getter: read like a property
    return this.#balance;
  }

  static compare(a, b) {
    return a.balance - b.balance;
  }
}

const a = new BankAccount("Uma").deposit(50).deposit(25);
const b = new BankAccount("Vic").deposit(100);

console.log(a.id, a.owner, a.balance, a.transactions);
console.log(b.id, BankAccount.bankName);
console.log([b, a].sort(BankAccount.compare).map((acc) => acc.owner));
console.log(a.balance === 75, "#balance" in a);
1 Uma 75 [ '+50', '+25' ]
2 JS Bank
[ 'Uma', 'Vic' ]
true false

Trying to access a.#balance from outside the class is a syntax error — real privacy, not just a naming convention.

Inheritance with extends

A class can extend another class, inheriting its fields and methods and adding or overriding its own. Inside the child constructor, call super(…) before using this; inside methods, super.method() calls the parent's version:

js · try it yourself
class Shape {
  constructor(name) {
    this.name = name;
  }
  area() {
    return 0;
  }
  toString() {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(radius) {
    super("Circle");
    this.radius = radius;
  }
  area() {
    return Math.PI * this.radius ** 2;
  }
}

class Square extends Shape {
  constructor(side) {
    super("Square");
    this.side = side;
  }
  area() {
    return this.side ** 2;
  }
  toString() {
    return super.toString() + ` (side ${this.side})`;
  }
}

const shapes = [new Circle(1), new Square(3), new Circle(2.5)];
for (const s of shapes) console.log(String(s));
console.log(shapes[1] instanceof Square, shapes[1] instanceof Shape);
Circle with area 3.14
Square with area 9.00 (side 3)
Circle with area 19.63
true true

Each shape answers area() in its own way, but the loop treats them all the same — this is polymorphism.

Classes are functions underneath

class is mostly cleaner syntax for JavaScript's prototype system: methods live on ClassName.prototype and are shared by all instances. The Prototypes chapter explains what happens behind the scenes.

js · try it yourself
class Dog {
  bark() {
    return "Woof";
  }
}
const rex = new Dog();
const fido = new Dog();
console.log(rex.bark === fido.bark);                     // one shared method
console.log(Object.getPrototypeOf(rex) === Dog.prototype);
console.log(Object.getOwnPropertyNames(Dog.prototype));
true
true
[ 'constructor', 'bark' ]

Key points

Feature Syntax
Constructor constructor(a, b) { this.a = a; }
Method name() { … }
Public field count = 0;
Private field / method #secret = 1; / #helper() { … }
Getter / setter get total() { … } / set total(v) { … }
Static member static create() { … }
Inheritance class B extends A { … } + super(…)

Tip: Classes are always in strict mode, and — unlike function declarations — they are not usable before their definition.

Test yourself

Which method runs automatically when you create an instance with new?

  1. init()
  2. constructor()
  3. create()
  4. new()

In a subclass constructor, what must you call before using this?

  1. this.parent()
  2. super()
  3. extends()
  4. Object.create()

How do you declare a private field in a class?

  1. private count = 0;
  2. _count = 0;
  3. #count = 0;
  4. static count = 0;