Back to Curriculum

Classes and Object-Oriented Programming

📚 Lesson 9 of 20 ⏱️ 45 min

Classes and Object-Oriented Programming

45 min

While JavaScript is prototype-based, ES6 introduced the `class` syntax to make Object-Oriented Programming (OOP) more accessible and familiar to developers coming from languages like Java or C#.

A **Class** is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods). The `constructor` method is a special method for initializing new objects.

**Inheritance** allows a class to derive properties and methods from another class using `extends`. The `super` keyword is used to call the parent class's constructor or methods.

**Encapsulation** (hiding internal details) is supported via private fields (prefixed with `#`). **Polymorphism** allows child classes to override parent methods to provide specific implementations.

Key Concepts

  • Class declaration and Constructor.
  • Inheritance (`extends`, `super`).
  • Getters and Setters.
  • Static methods and properties.
  • Private fields (`#private`).

Learning Objectives

Master

  • Creating class hierarchies
  • Using static methods for utility functions
  • Implementing encapsulation with private fields
  • Overriding methods in subclasses

Develop

  • Object-Oriented Design principles (SOLID)
  • Code organization and modularity
  • Understanding the prototype chain under the hood

Tips

  • Use classes for entities that need to maintain internal state (e.g., `User`, `Game`, `ShoppingCart`).
  • Use `static` methods for utility functions that don't need an instance (e.g., `Math.max`).
  • Prefer composition over deep inheritance hierarchies (Composition vs. Inheritance).
  • Use getters/setters to validate data before setting a property.

Common Pitfalls

  • Forgetting to call `super()` in a subclass constructor (throws an error).
  • Overusing classes when simple functions or objects would suffice (JS is not Java).
  • Confusing class methods with arrow functions (arrow functions in classes are instance properties, not prototype methods).
  • Trying to access private fields (`#field`) from outside the class.

Summary

  • Classes provide structure for OOP.
  • Inheritance enables code reuse.
  • Encapsulation protects internal state.
  • It's syntax sugar over prototypes.

Exercise

Create a `Car` class with a constructor, methods, and inheritance.

class Car {
  constructor(brand) {
    this.brand = brand;
  }

  start() {
    return `${this.brand} is starting...`;
  }
}

const myCar = new Car("Toyota");
console.log(myCar.start());

Exercise Tips

  • Add a child class using extends: class ElectricCar extends Car.
  • Use super() to call the parent constructor in the child class.
  • Add private fields with # prefix: #batteryLevel = 100.
  • Override parent methods in child classes to demonstrate polymorphism.

Code Editor

Output