Dependency Injection
The goal of dependency injection is to decouple objects from their dependencies as much as possible.
This means to decouple how the dependencies are selected, but not how they are used.
How a dependency is used depends on abstractions: the client code expects a particular interface and does not care what the dependency object is as long as it provides the interface. This works particularly well in JavaScript where duck-typing is favored over class inheritance.
The solution for decoupling the selection is to move the responsibility of selecting the actual dependency to another piece of code. This decoupling of is the implementation of a principle that Martin Fowler calls "Inversion of Control," and Robert C. Martin titles "Dependency Inversion," the fifth of his SOLID principles of object-oriented development (Fowler, Martin). They have more to say about that than I do! What I will discuss here are the forms that decoupling can take in JavaScript.
How a dependency is used depends on abstractions: the client code expects a particular interface and does not care what the dependency object is as long as it provides the interface. This works particularly well in JavaScript where duck-typing is favored over class inheritance.
The solution for decoupling the selection is to move the responsibility of selecting the actual dependency to another piece of code. This decoupling of is the implementation of a principle that Martin Fowler calls "Inversion of Control," and Robert C. Martin titles "Dependency Inversion," the fifth of his SOLID principles of object-oriented development (Fowler, Martin). They have more to say about that than I do! What I will discuss here are the forms that decoupling can take in JavaScript.