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

Three Approaches to Object Creation

Compare classes, factory functions, and mixins as distinct strategies for creating and organizing objects in JavaScript.

Three Approaches to Object Creation

You'll learn the three main strategies for creating and organizing objects in JavaScript, each with different trade-offs.

The Core Idea

JavaScript offers multiple ways to create objects beyond simple object literals. The three most common patterns are classes (blueprint-based), factory functions (function-based), and mixins (composition-based). Each solves the same problem—creating multiple related objects—but with different philosophies.

Classes

Classes use the class keyword to define a blueprint. Objects created with new inherit methods from the class prototype:

class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, ${this.name}`;
  }
}
const user = new User('Alice');

Classes are familiar, explicit, and memory-efficient (methods are shared).

Factory Functions

Factory functions return new objects directly—no new keyword required:

function createUser(name) {
  return {
    name: name,
    greet() {
      return `Hello, ${name}`;
    }
  };
}
const user = createUser('Alice');

Factories are flexible, avoid this confusion, and easily support closures.

Mixins

Mixins compose objects by combining properties from multiple sources:

const canGreet = { greet() { return `Hello, ${this.name}`; } };
const canWalk = { walk() { return 'Walking...'; } };

const user = Object.assign({ name: 'Alice' }, canGreet, canWalk);

Mixins excel at composition—building objects from reusable pieces without rigid inheritance.

Choosing an Approach

Classes fit when you need traditional inheritance hierarchies. Factories work well for encapsulation and avoiding prototype complexity. Mixins shine when you want to compose behaviors from multiple sources.

Key Takeaway: Classes provide inheritance-based blueprints, factory functions offer flexible closure-based creation, and mixins enable composition without inheritance—each pattern suits different architectural needs.