Classes in JavaScript - OOP
⭐ JavaScript Classes in OOP – The Ultimate, Super-Detailed Guide (With Examples for Every Case)
If you’ve ever used JavaScript and wondered: “How do people design reusable, scalable code?” The answer is → OOP (Object-Oriented Programming) And the heart of OOP in JavaScript is → Classes
This post will take you from zero to absolute mastery of JS classes—covering everything including syntax, inheritance, super(), static methods, private fields, getters/setters, and all hidden behaviours.
🔶 1. What Are Classes in JavaScript?
A class in JavaScript is a blueprint for creating objects.
It tells JavaScript:
- what properties every object created from this class should have
- what actions (methods) these objects can perform
👉 Think of a class like a template or mold. 👉 And objects created from the class are like copies made from that mold.
Example (Very Simple Class)
class Person {}
This creates a class, but it's empty.
To make it useful, we add:
- properties (via constructor)
- methods
🔶 2. The constructor() Method – Entry Point of Every Object
The constructor is a special method that runs automatically whenever you create an object using new.
Example
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const p1 = new Person("Alice", 22);
console.log(p1.name); // Alice
console.log(p1.age); // 22
Key Points:
- Only one constructor allowed per class.
thisrefers to the current object created.
🔶 3. Adding Methods to Classes
Methods define what objects can do.
Example:
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hello, I am ${this.name}`);
}
}
const p = new Person("Dev");
p.sayHi();
🔶 4. Class Expressions (Not Just Class Declarations)
Classes can also be stored in variables.
Example:
const Car = class {
drive() {
console.log("Driving...");
}
};
new Car().drive();
🔶 5. Getters & Setters (Super Useful for Validations)
Example:
class User {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(value) {
if (value.length < 3) {
console.log("Name too short");
return;
}
this._name = value;
}
}
const u = new User("dev");
console.log(u.name); // DEV
u.name = "Al"; // Name too short
Why useful?
- You can control how values are read/written
- Can transform values (uppercase example)
- Can validate data
🔶 6. Static Methods & Properties
Static = belongs to class, not to objects.
Example:
class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(5, 10)); // 15
Trying to use on an object gives error:
const m = new MathUtil();
m.add(3, 4); // ❌ TypeError
🔶 7. Inheritance – Extending Classes
This is the most powerful OOP feature.
Example:
class Animal {
eat() {
console.log("Eating");
}
}
class Dog extends Animal {
bark() {
console.log("Barking");
}
}
const d = new Dog();
d.eat(); // inherited
d.bark(); // own method
What’s happening?
- Dog inherits all methods of Animal
- Dog can add its own methods too
🔶 8. super() – Calling Parent Constructor
If subclass has its own constructor, you must call super() first.
Example:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // MUST
this.breed = breed;
}
}
const d = new Dog("Tommy", "Labrador");
console.log(d.name); // Tommy
console.log(d.breed); // Labrador
🔶 9. Private Fields (#)
Private fields are accessible only inside class.
Example:
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
acc.deposit(100);
console.log(acc.getBalance()); // 100
console.log(acc.#balance); // ❌ SyntaxError
Best use case:
- passwords
- internal counters
- sensitive data
🔶 10. Private Methods
You can also hide methods.
class User {
#calculateScore() {
return 100;
}
getScore() {
return this.#calculateScore();
}
}
const u = new User();
console.log(u.getScore()); // 100
console.log(u.#calculateScore()); // ❌ Error
🔶 11. Class Fields (Public Properties)
You can directly define properties without constructor.
Example:
class Student {
grade = "A";
}
const s = new Student();
console.log(s.grade); // A
🔶 12. Overriding Methods
A child class can replace behaviour of parent class.
Example:
class Animal {
sound() {
console.log("Some sound");
}
}
class Cat extends Animal {
sound() {
console.log("Meow Meow");
}
}
new Cat().sound(); // Meow Meow
🔶 13. Polymorphism (Same Method, Different Behaviour)
Same method name, different implementation.
Example:
class Bird {
fly() {
console.log("Bird is flying");
}
}
class Penguin extends Bird {
fly() {
console.log("Penguins can’t fly");
}
}
new Bird().fly(); // Bird is flying
new Penguin().fly(); // Penguins can’t fly
🔶 14. Instances & instanceof
Check whether an object belongs to a class.
class Hero {}
const h = new Hero();
console.log(h instanceof Hero); // true
console.log(h instanceof Object); // true
🔶 15. Real Life Example – Building a Mini OOP System
Step 1: Base Class
class User {
constructor(username) {
this.username = username;
}
login() {
console.log(`${this.username} logged in`);
}
}
Step 2: Admin Extends User
class Admin extends User {
deleteUser(user) {
console.log(`Deleted user: ${user.username}`);
}
}
Step 3: Use the System
const user1 = new User("dev");
const admin = new Admin("superadmin");
user1.login(); // dev logged in
admin.login(); // superadmin logged in
admin.deleteUser(user1);
🔶 16. When Should You Use Classes in JavaScript?
Use classes when you need:
✔ Reusable templates ✔ Organized code ✔ Maintainable structure ✔ Large-scale applications ✔ OOP patterns (inheritance, polymorphism, encapsulation)
Perfect for:
- Games
- E-commerce systems
- APIs
- UI Component systems
- Custom HTML Elements (Web Components)
- User authentication systems
- Data models
🔶 17. Common Mistakes to Avoid
❌ Forgetting super() inside child constructors
❌ Trying to access private fields outside class
❌ Using static methods on objects instead of class
❌ Confusing class fields with constructor assignments
❌ Thinking JS classes work exactly like Java (they don’t—they are “syntactic sugar” over prototypes)
🎉 Final Summary
JavaScript Classes give you:
| Feature | Description |
|---|---|
| Constructor | Initialize properties |
| Methods | Define actions |
| Inheritance | Reuse parent class |
| super() | Call parent constructor/method |
| Static methods | Class-level utilities |
| Private fields | Hide internal data |
| Getters/Setters | Controlled read/write |
| Polymorphism | Custom method behavior |
Classes help write code that is:
- clean
- structured
- scalable
- easy to maintain
- perfect for professional JS development
If you'd like, I can also write posts on:
✅ Prototypes behind the scenes ✅ OOP pillars in JS (Encapsulation, Abstraction, Inheritance, Polymorphism) ✅ Differences between function constructors vs classes ✅ Real-world project using classes
Just tell me the next topic!
Comments
Post a Comment