Course contentsShow
← JavaScript
Lesson 1805 of 2,72338. Object-Oriented PatternsFree lesson

Class-Based Object Creation Review

Revisit how ES6 classes encapsulate data and behavior using constructors, methods, and the prototype chain.

Class-Based Object Creation Review

You'll learn how ES6 classes bundle data and behavior together using a clean, familiar syntax built on JavaScript's prototype system.

The Core Idea

ES6 classes provide a structured way to create objects with shared methods. Under the hood, they're syntactic sugar over JavaScript's prototype chain, but they make object creation cleaner and more intuitive. A class acts like a blueprint: it defines what data each instance holds (via the constructor) and what behaviors all instances share (via methods).

Think of a class like a cookie cutter. The constructor shapes the unique properties of each "cookie" (object instance), while methods are shared recipes that all cookies from that cutter can use.

How Classes Work

When you define a class, the constructor runs once per instance, setting up initial properties. Methods you define inside the class automatically live on the class's prototype, so all instances share the same function references in memory—efficient and organized.

class Rectangle {
  constructor(width, height) {
    this.width = width;   // instance data
    this.height = height;
  }

  area() {  // prototype method
    return this.width * this.height;
  }
}

const rect = new Rectangle(10, 5);
rect.area();  // 50

Here, width and height are unique to each instance. The area method is shared via Rectangle.prototype, so creating 100 rectangles doesn't create 100 copies of the area function.

Why It Matters

Classes encapsulate related data and behavior in one place. They keep your code organized, make your intent clear, and leverage the prototype chain for memory efficiency. Compared to factory functions or manual prototype manipulation, classes offer a familiar, standardized approach.

Key Takeaway: ES6 classes use constructors to initialize instance-specific data and methods to define shared behavior through the prototype chain, combining clarity with efficiency.