(Modeling real-world data using objects and blueprints)
Object-Oriented Programming (OOP) is a programming style based on objects. JavaScript supports OOP using both constructor functions and ES6 classes.
Key OOP concepts:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const alice = new Person("Alice", 25);
alice.greet(); // Hello, my name is Aliceconstructor() is called automatically when creating a new object using new.this refers to the new object being created.You can create a child class that inherits from a parent class using extends.
class Employee extends Person {
constructor(name, age, role) {
super(name, age); // Calls parent constructor
this.role = role;
}
work() {
console.log(`${this.name} is working as a ${this.role}`);
}
}
const bob = new Employee("Bob", 30, "Developer");
bob.greet(); // Hello, my name is Bob
bob.work(); // Bob is working as a DeveloperJavaScript supports private fields using # syntax (ES2022+).
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
acc.deposit(1000);
console.log(acc.getBalance()); // 1000
// console.log(acc.#balance); // ❌ Error: Private fieldChild classes can override parent methods:
class Animal {
speak() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}
const d = new Dog();
d.speak(); // Dog barks| Feature | Constructor Function | ES6 Class Syntax |
|---|---|---|
| Syntax | Function-based | Cleaner, class-based |
| Inheritance | Via prototype | Using extends, super |
| Private fields | Not supported (older) | Supported with # |
| Readability | Moderate | Better |
Think of a Car class as a blueprint.
Each object created from it (like myCar, yourCar) is an actual car with its own data but follows the same design.
constructor() to initialize values.extends and super().# for private fields (ES2022+).Book class with title, author, and a getSummary() method.Book into a Magazine class with an extra issue property.#password and methods to change it.