Course contentsShow
← JavaScript
Lesson 520 of 2,72313. ClosuresFree lesson

Closure-Based Dependency Injection

Inject dependencies at factory creation time and make them available to all returned methods.

Closure-Based Dependency Injection

What You'll Learn: How to inject dependencies when creating a factory function so all returned methods can access them without passing them around repeatedly.

The Core Idea

Dependency injection means providing the external things (dependencies) a function needs to do its work. With closures, you can "inject" these dependencies at factory creation time — they become part of the closure's lexical scope, making them available to all the methods you return.

Think of it like packing a toolbox: instead of handing a worker individual tools every time they need them, you give them a fully-stocked toolbox once at the start of their shift. Every task they perform has immediate access to those tools.

How It Works

When you create a factory function, accept the dependencies as parameters. Any functions you create and return inside that factory will capture those dependencies in their closure:

function createLogger(prefix, outputFn) {
  // Dependencies: prefix, outputFn
  
  return {
    info(message) {
      outputFn(`${prefix} [INFO]: ${message}`);
    },
    error(message) {
      outputFn(`${prefix} [ERROR]: ${message}`);
    }
  };
}

const logger = createLogger('MyApp', console.log);
logger.info('Started');  // MyApp [INFO]: Started
logger.error('Failed');  // MyApp [ERROR]: Failed

Notice how info and error don't need prefix or outputFn passed to them — they already have them via closure. You injected them once during creation.

This pattern keeps your methods clean, lets you swap dependencies easily (useful for testing), and leverages the closure pattern you already understand.

Key Takeaway: Closure-based dependency injection captures external dependencies at factory creation time, making them available to all returned methods without repetitive parameter passing.