Dependency Injection is a pattern where instead of creating or requiring dependencies directly inside a module, we pass them as paramaeters or reference.

// foo.js
export default class Foo {
    print() {
        console.log('Hello world!');
    }
}

//baz.js
import Foo from './foo.js';

export default class Baz {
    constructor() {
        this.foo = new Foo();
    }
}

//app.js
import Baz from './baz.js';

let b = new Baz();
// Using Dependecy Injection
// Updated baz.js
export default class Baz {
    constructor(foo) {
        this.foo = foo;
    }
}

//app.js
import Foo from './foo.js';
import Baz from './baz.js';

let b = new Baz(new Foo()); // Foo instance is passed as parameter to Baz

Benefits

  • Unit testing - Avoid need for stubbing
  • Flexibility - Freedom to change implementation at any point

References: