Topic 23 of 59 JavaScript Decision Making & Control Flow Interactive Tutorial

Object-Oriented JavaScript: Objects, Classes, Methods, and Design Concepts

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is Object-Oriented JavaScript? Core Concept & Direct Summary

Core Objective & Problem Statement

What are the core OOP pillars supported in modern JavaScript?

Direct Answer Summary
JavaScript supports OOP principles including Encapsulation (private fields #), Abstraction, Inheritance (extends), and Polymorphism.

So far in this series, your programs have beenscripts— instructions that run top to bottom. That works great for small tools. But imagine building a game with 50 players, a shop with 1,000 products, or a school system with 500 students. You can't writestudent1Name,student1Age,student2Name,student2Age… forever. 😵

Professional developers solve this withObject-Oriented Programming (OOP)— a way of organizing code aroundobjects: self-contained bundles that hold bothdata(properties) andbehavior(methods) together.

Think of it like this:

  • 🍪 Aclassis the cookie cutter — the blueprint
  • 🍪🍪🍪Objectsare the cookies — real things made from the blueprint

In this lesson, you'll go from "I know what an object is"  to designing your own classes, creating objects from them, and understanding the four pillars of OOP that every interview asks about. Let's build. 🏗️

How Does Object-Oriented JavaScript Work? In-Depth Mechanics & Architecture

JavaScript is prototype-based underneath ES6 class syntax sugar. Classes provide clear constructors and class fields.

Part 1: Objects — The Foundation (Quick Recap+)

From Lesson 5, an object bundles related data as key-value pairs:

script.js
Run Online
const student = {
  name: "Priya", age: 22, course: "JavaScript"
};

But objects hold more than data — they holdfunctionstoo. A function inside an object is called amethod:

script.js
Run Online
const student = {
  name: "Priya", age: 22, // 👇 a method — a function that belongs to this object  introduce() {    console.log(`Hi, I'm ${this.name} and I'm ${this.age}.`);  }};
  student.introduce();
  // "Hi, I'm Priya and I'm 22."

🔑 Meetthis— The Object Talking About Itself

thisinside a method means"this object — the one calling the method."

script.js
Run Online
const student = {
  name: "Priya", introduce() {
    console.log(this.name);
    // this = student → "Priya"
  }
};

It's how a method reaches itsownobject's data instead of some random variable. (We'll flagthisquirks as we go — it has famous edge cases!)


Part 2: The Problem — Copy-Paste Objects

One student works fine. Ten students? Disaster:

script.js
Run Online
// 😩 The repetitive nightmare:
const s1 = {
  name: "Priya", age: 22, introduce() {
    console.log(this.name);
  }
};
const s2 = {
  name: "Amit", age: 24, introduce() {
    console.log(this.name);
  }
};
const s3 = {
  name: "Riya", age: 21, introduce() {
    console.log(this.name);
  }
};
// … imagine 500 of these. And what if introduce() needs a fix? 500 edits! 💀

Same shape, same methods, repeated endlessly. Whenever you see this pattern, you need ablueprint— aclass.


Part 3: Classes — The Blueprint 🏭

Aclassdefines the structure once; you then manufacture as many objects ("instances") as you want:

script.js
Run Online
class Student {
  // 🏗️ The constructor runs automatically when you create an object
  constructor(name, age) {
    this.name = name;
    // "this new object's name = the name passed in"
    this.age = age;
  } // A shared method — every Student gets this behavior
  introduce() {
    console.log(`Hi, I'm ${this.name}, ${this.age} years old 👋`);
  }
}// 🍪 Manufacturing objects with "new":
const s1 = new Student("Priya", 22);
const s2 = new Student("Amit", 24);
const s3 = new Student("Riya", 21);
s1.introduce();
// "Hi, I'm Priya, 22 years old 👋"
s2.introduce();
// "Hi, I'm Amit, 24 years old 👋"
s3.introduce();
// "Hi, I'm Riya, 21 years old 👋"

Anatomy of a Class

script.js
Run Online
class Student {
  constructor(name, age) {
    // ① special method — runs on "new Student(...)"
    this.name = name;
    // ② stores the passed value ON the new object
    this.age = age;
  } introduce() {
    // ③ a method — shared behavior
    console.log(this.name);
  }
}
PieceJob
class StudentDeclares the blueprint (capital letter = class convention!)
constructor(…)The setup function — runs once per new object
this.name = nameAttaches data to the specific object being built
new Student("Priya", 22)Creates aninstance— a real object from the blueprint

The class vs instance moment of clarity:

script.js
Run Online
console.log(s1.name);
// "Priya" — HER data
console.log(s2.name);
// "Amit"  — HIS data
s1.introduce();
// uses s1's data — shared behavior, individual data ✅

One blueprint. Unlimited independent objects.Thisis how real applications manage thousands of users, products, and posts.

Part 4: Methods in Action — A Real Mini-System

Classes shine when objects havebehavior, not just data. Watch a bank account come alive:

script.js
Run Online
class BankAccount {
  constructor(owner, balance = 0) {
    // = 0 is a DEFAULT value!    this.owner = owner;    this.balance = balance;  }
    deposit(amount) {
      this.balance += amount;
      console.log(`💰 +₹${amount} → Balance: ₹${this.balance}`);
    } withdraw(amount) {
      if (amount > this.balance) {
        console.log(`❌ ${this.owner}: insufficient funds!`);
        return;
      } this.balance -= amount;
      console.log(`💸 -₹${amount} → Balance: ₹${this.balance}`);
    }
  }const account = new BankAccount("Priya", 1000);
  account.deposit(500);
  // 💰 +₹500 → Balance: ₹1500account.withdraw(2000);   // ❌ Priya: insufficient funds!account.withdraw(300);    // 💸 -₹300 → Balance: ₹1200

Notice what the class gave us:

  • Data (balance) and therulesfor changing it (withdrawchecks funds) live together
  • Every account validates itself — no external code can accidentally create a broken state
  • This isencapsulation— Pillar #1, arriving in a moment 👀

Part 5: The Four Pillars of OOP 🏛️

Every OOP interview asks about these. Here's each one — in plain JavaScript:

1️⃣ Encapsulation — Keep Data and Its Rules Together 🔒

Bundle data with the methods that safely manage it — and hide what shouldn't be touched. Modern JavaScript has true private fields with#:

script.js
Run Online
class Wallet {
  #balance = 0;
  // 🔒 truly private — invisible outside!
  addMoney(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  } getBalance() {
    return `₹${this.#balance}`;
    // read through a controlled door
  }
}const wallet = new Wallet();
wallet.addMoney(500);
console.log(wallet.getBalance());
// "₹500"
console.log(wallet.#balance);
// ❌ SyntaxError — private!

(Remember the closure-based privacy fromLesson 22?#fieldsare the modern, cleaner version of that same idea.)

2️⃣ Inheritance — Build New Classes From Old Ones 🧬

ACaris aVehicle. ASavingsAccountis aBankAccount. Inheritance lets a class reuse and extend another:

script.js
Run Online
class Vehicle {
  constructor(brand) {
    this.brand = brand;
  } start() {
    console.log(`${this.brand} engine started 🔑`);
  }
}// Car INHERITS everything from Vehicle:
class Car extends Vehicle {
  honk() {
    console.log(`${this.brand} says: Beep beep! 📢`);
  }
}const myCar = new Car("Toyota");
myCar.start();
// "Toyota engine started 🔑" — inherited from Vehicle!
myCar.honk();
// "Toyota says: Beep beep! 📢" — Car's own method

extendscreates the parent-child link. The child gets everything the parent has, plus its own additions.

super — Calling the Parent

script.js
Run Online
class ElectricCar extends Vehicle {
  constructor(brand, batterySize) {
    super(brand);
    // ☎️ call the parent's constructor first!
    this.batterySize = batterySize;
  } charge() {
    console.log(`${this.brand} charging ${this.batterySize}kWh 🔋`);
  }
}const tesla = new ElectricCar("Tesla", 75);
tesla.start();
// "Tesla engine started 🔑" (inherited)
tesla.charge();
// "Tesla charging 75kWh 🔋" (own)

⚠️ Rule:in a child class constructor, you must callsuper()beforeusingthis. Forget it → ReferenceError.

3️⃣ Polymorphism — Same Method, Different Behavior 🎭

Children canoverrideparent methods with their own versions:

script.js
Run Online
class Animal {
  speak() {
    console.log("Some generic animal sound…");
  }
}class Dog extends Animal {
  speak() {
    console.log("Woof! 🐕");
  }
}class Cat extends Animal {
  speak() {
    console.log("Meow! 🐈");
  }
}const animals =[new Dog(), new Cat(), new Animal()];
for (let animal of animals) {
  animal.speak();
  // same command — each responds its OWN way!
}// Woof! 🐕
// Meow! 🐈
// Some generic animal sound…

One interface (speak()), many forms — that's polymorphism ("many shapes"), and it makes code beautifully extensible: add aCowclass later, and the loop just works.

4️⃣ Abstraction — Hide Complexity, Show Simplicity 🎛️

Users shouldn't need to knowhowthings work inside — just the simple controls:

script.js
Run Online
class CoffeeMachine {
  brew() {
    this.#heatWater();
    // complex steps…
    this.#grindBeans();
    // …hidden inside
    this.#pour();
    console.log("☕ Your coffee is ready!");
  } #heatWater() {
    console.log("  (heating to 94°C…)");
  } #grindBeans() {
    console.log("  (grinding beans…)");
  } #pour() {
    console.log("  (pouring…)");
  }
}const machine = new CoffeeMachine();
machine.brew();
// one simple button — complexity hidden ✅

You press one button; the machine handles the engineering. Your TV remote, your car's steering wheel, and every good class work this way.

🛠️ Mini Project: RPG Character System ⚔️

All four pillars in one tiny game system:

script.js
Run Online
// ⚔️ RPG Character System
class Character {
  #health = 100;
  // 🔒 encapsulation
  constructor(name) {
    this.name = name;
  } attack() {
    console.log(`${this.name} attacks! ⚔️`);
  } takeDamage(amount) {
    this.#health -= amount;
    console.log(`${this.name} takes ${amount} damage! (${this.#health} HP left)`);
  } getHealth() {
    return this.#health;
  }
}class Warrior extends Character {
  // 🧬 inheritance
  attack() {
    // 🎭 polymorphism — own version!
    console.log(`${this.name} swings a mighty sword! 🗡️💥`);
  }
}class Mage extends Character {
  attack() {
    console.log(`${this.name} casts a fireball! 🔥✨`);
  }
}const hero = new Warrior("Arjun");
const wizard = new Mage("Gandalf");
hero.attack();
// Arjun swings a mighty sword! 🗡️💥
wizard.attack();
// Gandalf casts a fireball! 🔥✨
hero.takeDamage(30);
// Arjun takes 30 damage! (70 HP left)
console.log(hero.#health);
// ❌ SyntaxError — health is private!

Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
const s = Student("Priya", 22)(nonew)TypeError — classes REQUIREnewnew Student("Priya", 22)
Usingthisbeforesuper()in child constructorReferenceErrorsuper(…)is the child's FIRST line
Naming classes lowercase (class student)Works, but breaks universal conventionclass Student— PascalCase always
Losingthisin callbacksthisbecomes undefined 😱Use arrow functions for callbacks (next lessons!)
Methods written with commas between themSyntaxErrorNo commas between class methods!
Modifying data directly instead of via methodsBroken rules, invalid statesEncapsulate — control changes through methods

⚠️ The comma trap— classes are NOT object literals:

script.js
Run Online
class Student {
  constructor(name) {
    this.name = name;
  } // ← no comma here!
  introduce() {
    console.log(this.name);
  } // ← no comma here either!
}

Quick Self-Check: Lesson 23 Quiz 🧠

  1. What's the difference between a class and an object?
  2. What does theconstructormethod do, and when does it run?
  3. What's the output?
    script.js
    Run Online
    class Animal {
      speak() {
        console.log("…");
      }
    }class Dog extends Animal {
      speak() {
        console.log("Woof!");
      }
    }new Dog().speak();
  4. Why must a child class callsuper()before usingthis?
  5. Name the four pillars of OOP.

(Answers: 1. A class is the blueprint; an object is a real instance built from it (cookie cutter vs cookie) · 2. It initializes each new object — runs automatically when you writenew ClassName(...)· 3. "Woof!" — the child's overridden method wins (polymorphism) · 4. The parent must set up its part of the object first; JavaScript enforces this with a ReferenceError · 5. Encapsulation, inheritance, polymorphism, abstraction)

JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
class BankAccount {
  #balance = 0;
  // Private field
  constructor(initialDeposit) {
    this.#balance = initialDeposit;
  } deposit(amount) {
    this.#balance += amount;
  } getBalance() {
    return this.#balance;
  }
}const acc = new BankAccount(100);
acc.deposit(50);
console.log(acc.getBalance());
// 150

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q: Are JavaScript classes dynamic like prototype objects?

A: Yes, classes in JS are syntactic sugar over prototypal inheritance and remain standard function objects underneath.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations