Class in JavaScript

📌 What is a Class in JavaScript?

A class in JavaScript is a blueprint for creating objects with shared properties and methods. It was introduced in ES6 as a syntactic sugar over JavaScript's existing prototype-based inheritance. While the class syntax looks similar to classes in other languages, it's still built on top of prototypes.

Note

💡 Under the hood, JavaScript classes still use prototype-based inheritance — the class syntax just makes it easier and more intuitive to work with.

🧱 Defining a Class

Basic Class Definition

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

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const p1 = new Person("Alice", 30);
p1.greet(); // Hello, my name is Alice.

⚙️ Constructor Method

The constructor() is a special method used to initialize new objects. It runs automatically when a new object is created using the new keyword.

🧠 Instance Methods

Any method defined inside a class (but outside the constructor) becomes an instance method shared by all instances via the prototype.

📐 Class Inheritance

You can create a class that inherits from another using the extends keyword and call the parent constructor using super().

Class Inheritance Example

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

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const d = new Dog("Rex");
d.speak(); // Rex barks.

🔒 Getters and Setters

Classes can define get and set methods to control access to properties.

Getter and Setter Example

class Circle {
  constructor(radius) {
    this._radius = radius;
  }

  get diameter() {
    return this._radius * 2;
  }

  set diameter(d) {
    this._radius = d / 2;
  }
}

const c = new Circle(5);
console.log(c.diameter); // 10
c.diameter = 20;
console.log(c.diameter); // 20

🧩 Static Methods

Static methods are called on the class itself, not on instances. They are defined using the static keyword.

Static Method Example

class MathUtils {
  static square(x) {
    return x * x;
  }
}

console.log(MathUtils.square(4)); // 16

🧾 Summary

  • 🔧 Use class to define object blueprints.
  • 🏗️ constructor() initializes instance properties.
  • 📦 Instance methods are shared via the prototype.
  • 🔁 Inheritance via extends and super().
  • 🧮 Static methods belong to the class itself.
  • 🔐 Getters/setters for controlled property access.

📚 Learn More

>>“Classes in JavaScript don’t change how inheritance works — they make it easier to write and understand.” 🌱