Reading history

JavaScript Classes: Constructor, Private Fields, extends

4 min read 1 views

Learn JavaScript classes: constructors, methods, private # fields, getters, inheritance with extends and super, overriding and static methods.

A class is a blueprint for making objects that share the same shape and behaviour. Instead of writing out a fresh object literal for every bank account or every shape, you describe the structure once and create as many instances as you need with new. Classes also support inheritance, so a Circle can reuse everything a general Shape already does.

In this lesson you will learn

  • Writing a class with a constructor and methods
  • Creating objects with new
  • Private fields with # and getters
  • Inheritance with extends and super
  • Overriding methods and static methods

Constructor, Methods and Private Fields

class BankAccount {
  #balance = 0;                 // private field

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

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

  withdraw(amount) {
    if (amount > this.#balance) {
      console.log(`${this.owner}: not enough money`);
      return this;
    }
    this.#balance -= amount;
    return this;
  }

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

const acc = new BankAccount("Fatima");
acc.deposit(5000).withdraw(1200).withdraw(10000);
console.log(acc.owner, acc.balance);
console.log(acc instanceof BankAccount);
// console.log(acc.#balance); // SyntaxError: private field

Output

Fatima: not enough money
Fatima 3800
true
  • constructor() runs automatically when you write new BankAccount("Fatima"). It sets up the new object’s starting data on this.
  • Methods such as deposit() are written inside the class without the function keyword. Every instance shares them.
  • #balance is a private field. Code outside the class cannot read or change it, so the balance can only move through deposit and withdraw, which check the amounts. This is encapsulation.
  • get balance() is a getter: it runs a method but is read like a property, acc.balance, with no parentheses.
  • Returning this from a method allows chaining: acc.deposit(5000).withdraw(1200).
  • instanceof checks whether an object was made from a class.

Inheritance with extends

class Shape {
  constructor(name) {
    this.name = name;
  }
  area() {
    return 0;
  }
  describe() {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(r) {
    super("Circle");            // call the parent constructor first
    this.r = r;
  }
  area() {                      // override the parent method
    return Math.PI * this.r ** 2;
  }
}

class Rectangle extends Shape {
  constructor(w, h) {
    super("Rectangle");
    this.w = w;
    this.h = h;
  }
  area() {
    return this.w * this.h;
  }
  static square(side) {         // called on the class, not an object
    return new Rectangle(side, side);
  }
}

const shapes = [new Circle(3), new Rectangle(4, 5), Rectangle.square(6)];
for (const s of shapes) console.log(s.describe());
console.log(shapes[0] instanceof Shape);

Output

Circle with area 28.27
Rectangle with area 20.00
Rectangle with area 36.00
true
  • class Circle extends Shape makes Circle a child class that inherits describe() from Shape.
  • A child constructor must call super(...) before using this; it runs the parent’s constructor.
  • Defining area() again in the child overrides the parent version. describe() calls this.area(), so each shape automatically uses its own formula. Treating different objects through one shared interface like this is called polymorphism.
  • A static method belongs to the class itself: Rectangle.square(6). It is often used as a convenient “factory” for creating instances.

Classes vs Object Literals

UseWhen
Object literal { }One-off data, configuration, JSON from a server
ClassMany objects with the same structure and behaviour, or when you want private state and inheritance

Under the hood, JavaScript classes are built on prototypes: methods live on BankAccount.prototype and every instance links to it. The class syntax is a cleaner way to write the same thing.

Common Mistakes

  1. Forgetting new: calling BankAccount("x") throws “Class constructor cannot be invoked without ‘new'”.
  2. Using this before super() in a child constructor, which throws a ReferenceError.
  3. Passing a method as a callback, such as button.onclick = acc.deposit, which loses this. Wrap it: () => acc.deposit(100).
  4. Putting commas between methods as in an object literal; class bodies do not use them.

Practice Exercises

Exercise 1. Create a Student class with a name and a marks array, and a method average().

Show answer
class Student {
  constructor(name, marks) {
    this.name = name;
    this.marks = marks;
  }
  average() {
    return this.marks.reduce((s, m) => s + m, 0) / this.marks.length;
  }
}
console.log(new Student("Rina", [80, 90, 70]).average()); // 80

Exercise 2. Make a SavingsAccount that extends BankAccount and adds addInterest(rate).

Show answer
class SavingsAccount extends BankAccount {
  addInterest(rate) {
    return this.deposit(this.balance * rate);
  }
}
const s = new SavingsAccount("Tanim").deposit(1000).addInterest(0.05);
console.log(s.balance); // 1050

The child cannot touch #balance directly, so it uses the public getter and deposit().

Frequently Asked Questions

Are JavaScript classes the same as Java classes?

They look similar, but JavaScript classes are built on prototypes, are created at run time, and allow only single inheritance through extends. There are no interfaces or method overloading.

When were private fields added?

Private #fields became part of the language in ES2022 and work in all modern browsers and in current Node.js versions.

Summary

  • A class is a blueprint; new creates instances and runs the constructor.
  • #private fields protect data; getters expose it safely.
  • extends and super build child classes that reuse and override behaviour.
  • static methods belong to the class itself.

Next: JavaScript Error Handling.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *