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

When to Use Factory Functions

Identify scenarios where factory functions excel: avoiding 'this' issues and enabling composition.

When to Use Factory Functions

You'll learn: When factory functions are the right tool for the job and what problems they solve best.

Why Factory Functions Shine

Factory functions aren't always the answer, but they excel in specific scenarios where other patterns struggle. The two biggest wins are avoiding 'this' confusion and enabling clean composition.

Scenario 1: No 'this' Headaches

If you've ever lost this context when passing methods as callbacks or struggled with binding, factory functions eliminate that entirely. Because they use closure variables instead of this, there's nothing to lose:

// No 'this' to worry about
function createTimer(name) {
  let count = 0;
  
  return {
    increment() {
      count++; // Uses closure, not 'this'
      console.log(`${name}: ${count}`);
    }
  };
}

const timer = createTimer('MyTimer');
const increment = timer.increment;
increment(); // Works perfectly! No binding needed

Scenario 2: Composition Over Inheritance

When you need to mix behaviors from multiple sources, factory functions make composition straightforward. You can combine features from different factories without complex inheritance chains:

function canMove() {
  return {
    move() { console.log('Moving'); }
  };
}

function canShoot() {
  return {
    shoot() { console.log('Shooting'); }
  };
}

function createPlayer(name) {
  return {
    name,
    ...canMove(),
    ...canShoot()
  };
}

const player = createPlayer('Hero');
player.move();  // Moving
player.shoot(); // Shooting

When to Choose Them

Use factory functions when:

  • You want to avoid this binding issues entirely
  • You need to compose objects from multiple behaviors
  • You prefer functional programming patterns
  • Private state through closures is sufficient

Key Takeaway: Factory functions excel when you need this-free code or clean composition—choose them to eliminate context confusion and combine behaviors flexibly.