Course contentsShow
← JavaScript
Lesson 674 of 2,72316. Object Methods and PatternsFree lesson

Composition with Factory Functions

Compose multiple factories together to build complex objects from simpler building blocks.

Composition with Factory Functions

You'll learn how to combine multiple factory functions like LEGO bricks to create complex objects from simple, reusable pieces.

The Core Idea

Instead of building one giant factory function that does everything, you can write small, focused factories that each handle one responsibility. Then compose them together—meaning you call one factory, then mix its features into another factory's return object. This makes your code modular, testable, and easy to understand.

Think of it like building a meal: instead of one massive recipe, you have separate recipes for sauce, pasta, and seasoning. You combine them at the end to create the complete dish.

How It Works

Each factory returns an object with methods. To compose them, you create one object and add features from multiple factories using object spreading or Object.assign.

// Small, focused factories
function canEat(name) {
  return {
    eat(food) {
      console.log(`${name} is eating ${food}`);
    }
  };
}

function canWalk(name) {
  return {
    walk() {
      console.log(`${name} is walking`);
    }
  };
}

// Compose them into a complete object
function createDog(name) {
  return {
    name,
    ...canEat(name),
    ...canWalk(name)
  };
}

const dog = createDog('Rex');
dog.eat('kibble'); // "Rex is eating kibble"
dog.walk();        // "Rex is walking"

Here, createDog doesn't reinvent eating or walking—it composes those behaviors from smaller factories. You can reuse canEat and canWalk in a createCat factory too.

Why It Matters

Composition gives you flexibility. Need a robot that eats but doesn't walk? Compose only canEat. Need different combinations? Mix and match freely without inheritance hierarchies.

Key Takeaway: Composition with factory functions lets you build complex objects by combining simple, reusable behavior modules, making your code flexible and maintainable.