Lesson 4, by Codesarray, , 8 min read

JavaScript classes: constructor, extends, super, private fields

Learn JavaScript classes on one bank-account example: constructor and methods, getters and setters, static members, truly private #fields, inheritance with extends and super, and the proof that a class is a function underneath.

JavaScript classes look like a brand new piece of the language, but ask JavaScript itself and it answers honestly: typeof a class is "function". A class is the constructor-and-prototype pattern from the previous lesson written as one tidy block. This page builds a real BankAccount class piece by piece: constructor and methods, getters and setters with guards, static members, truly private #fields, and inheritance with extends and super. At the end we open the box and prove what class really builds. Everything here ran on Node 24.

A class is one block: constructor and methods

The class keyword takes a name and a block. Inside sit a constructor and the methods, with no commas between them (forgetting that is the number one typo). new runs the constructor with this pointing at a fresh object, and every method you write in the block goes straight onto the class's prototype: one copy, shared by everything the class builds.

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }
  deposit(amount) {
    this.balance += amount;
    return this.balance;
  }
  describe() {
    return `${this.owner} has ${this.balance} rupees`;
  }
}

const ada = new BankAccount("Ada", 100);
const ben = new BankAccount("Ben", 50);
console.log(ada.deposit(40));
console.log(ada.describe());
console.log(ben.describe());
console.log(ada.deposit === ben.deposit);
140
Ada has 140 rupees
Ben has 50 rupees
true

ada and ben are separate objects with their own data, but the last line is the interesting one: ada.deposit === ben.deposit is true. There is exactly one deposit function in memory, shared through the prototype. The class did the wiring you used to do by hand.

Private fields: the vault

In the version above, balance is a plain public property, so any code anywhere can write ada.balance = -50 and break the account. Real banks keep the money in a vault and make you talk to a teller. JavaScript's vault is a hash: a field named #balance is truly private. Only code inside the class block can touch it; outside the block, ada.#balance is not even a runtime error, it is a syntax error. Getters and setters are the teller window: get balance lets ada.balance read the vault with no parentheses, and set owner runs your guard code on a plain assignment.

class BankAccount {
  #owner;
  #balance;
  constructor(owner, balance) {
    this.#owner = owner;
    this.#balance = balance;
  }
  get balance() {
    return this.#balance;
  }
  get owner() {
    return this.#owner;
  }
  set owner(name) {
    if (name === "") throw new RangeError("owner cannot be empty");
    this.#owner = name;
  }
  deposit(amount) {
    if (amount <= 0) throw new RangeError("deposit must be positive");
    this.#balance += amount;
  }
}

const ada = new BankAccount("Ada", 100);
ada.deposit(40);
console.log(ada.balance);
ada.owner = "Ada Lovelace";
console.log(ada.owner);
try { ada.deposit(-5); } catch (err) { console.log(err.message); }
console.log(JSON.stringify(ada));
140
Ada Lovelace
deposit must be positive
{}

Note the private fields are declared at the top of the block; that is required. The bad deposit throws before anything changes, and the last line shows how private #fields really are: every field is private, so JSON.stringify(ada) prints an empty object.

static: the sign on the building

Some things belong to the bank itself, not to any one account: the name on the building, the count of accounts ever opened. Put static in front of a field or method and it lives on the class, not on the objects it builds. static stacks with #, so a static private field is the bank's own secret.

class BankAccount {
  static bankName = "Codes Bank";
  static #opened = 0;
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
    BankAccount.#opened += 1;
  }
  static report() {
    return `${BankAccount.bankName} has opened ${BankAccount.#opened} accounts`;
  }
}

const ada = new BankAccount("Ada", 100);
const ben = new BankAccount("Ben", 50);
console.log(BankAccount.bankName);
console.log(BankAccount.report());
console.log(ada.bankName);
Codes Bank
Codes Bank has opened 2 accounts
undefined

You read a static off the class name, and the constructor bumps the counter with BankAccount.#opened, not this. Ask ada for bankName and you get undefined: the accounts do not carry the building's sign.

Inheritance: extends and super

A savings account is a bank account, plus one extra idea: interest. extends draws that family line, and inside the child, super is the word for "my parent". In the constructor, super(...) runs the parent's constructor first — and that is the law: touch this before calling super() and the constructor throws. In any method, super.describe() runs the parent's version, so an override can build on the original instead of copying it.

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }
  describe() {
    return `${this.owner} has ${this.balance} rupees`;
  }
}

class SavingsAccount extends BankAccount {
  constructor(owner, balance, rate) {
    super(owner, balance);
    this.rate = rate;
  }
  addInterest() {
    this.balance += this.balance * this.rate;
  }
  describe() {
    return super.describe() + ` at ${this.rate * 100}% interest`;
  }
}

const mia = new SavingsAccount("Mia", 1000, 0.05);
mia.addInterest();
console.log(mia.describe());
console.log(mia instanceof SavingsAccount);
console.log(mia instanceof BankAccount);
Mia has 1050 rupees at 5% interest
true
true

mia is both things at once, and that is not magic: instanceof just asks whether a prototype appears anywhere up the chain, and extends linked the two prototypes into one chain, child first, then parent.

Classes are prototypes underneath

Time to open the box. Here is the previous lesson's User, reborn as a class, with every question from that lesson asked again.

class User {
  constructor(name) {
    this.name = name;
  }
  hello() {
    return `Hi, I'm ${this.name}`;
  }
}

const mia = new User("Mia");
const leo = new User("Leo");
console.log(typeof User);
console.log(Object.getPrototypeOf(mia) === User.prototype);
console.log(mia.hello === leo.hello);
console.log(Object.hasOwn(mia, "hello"));
console.log(mia instanceof User);
try { User("Zoe"); } catch (err) { console.log(err.message); }
function
true
true
false
true
Class constructor User cannot be invoked without 'new'

Every answer matches the hand-built version: a class is a function, the methods sit on User.prototype, the instances share one hello they do not own, and instanceof walks the chain. class is a better pen, not a different machine — but the pen adds ink. A class refuses to run without new (the old builder function would have run and broken quietly), class bodies always run in strict mode, and methods do not show up when you loop over an object's keys.

What you learned

  • class is the constructor-plus-prototype pattern in one block; typeof a class is "function".
  • The constructor runs on new and writes the object's own fields; methods go on the prototype, one copy shared.
  • #name makes a field truly private: a syntax error outside the block, invisible even to JSON.stringify.
  • get and set make functions look like properties, so reads and writes can follow rules.
  • static members live on the class itself; instances do not carry them.
  • extends links the prototypes; a child constructor must call super() before touching this, and super.method() reaches the parent's version.
  • instanceof walks the prototype chain, which is why a child instance passes for its parent too.

Common questions

Are JavaScript classes just syntactic sugar? Mostly, but not entirely. The object layout is identical to the hand-built constructor-and-prototype pattern. What class adds on top: it cannot be called without new, its body runs in strict mode, and its methods are non-enumerable. Private #fields have no equivalent in the old pattern at all.

Why does my subclass throw "Must call super constructor in derived class"? A child constructor's this does not exist until the parent constructor has built the object. If the constructor of a class with extends touches this (or returns) before calling super(), you get exactly that ReferenceError. Make super(...) the first line.

**What is the difference between #balance and the old _balance convention?** _balance is a plain public property with a polite underscore; any code can still read and change it. #balance is enforced by the language: outside the class block it is a syntax error, and it never appears in JSON.stringify or Object.keys.

When do I need a getter instead of a method? Use a getter when the thing reads like a property: ada.balance rather than ada.getBalance(). Use a method when the action takes arguments or clearly does work, like deposit(40). A setter is worth it when you want a guard to run on plain assignment.

**Do static methods see this?** Inside a static method, this is the class itself, so this.bankName works in report(). It is still clearer to name the class (BankAccount.bankName), and that is required for static private fields referenced from the constructor.

Next lesson: iterators and generators — how for...of really works, how to make your own objects loopable, and functions that pause themselves with yield.

This article goes with the video JavaScript Classes: constructor, extends, super, private fields. Watch it on YouTube.