Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. In JavaScript, there are several ways to do this:
1. Constructor Injection:
In this method, the dependencies are provided through a class’s constructor when creating the instance of that class.
Example:
```
function Car(Engine) { // Inject Engine dependency via constructor
this.engine = Engine;
}
let engine = new Engine();
let car = new Car(engine);
```
1. Property Injection:
In this case, the dependencies are given through public properties.
Example:
```
function Car() {
}
let car = new Car();
car.engine = new Engine(); // Injection via property
```
1. Method Injection:
With this approach, the dependency is given through methods.
Example:
```
class Car {
}
const car = new Car();
car.setEngine(new Engine()); // Injection via method
```
1. Parameter Injection:
Here the dependency is provided as a parameter.
Example:
```
function createCar(Engine) {
let car = {};
car.go = function() {
Engine.run();
}
return car;
}
let car = createCar(new Engine());
```
There are also many frameworks that offer built-in DI mechanisms. Some examples are Angular, Vue.js, and Nest.js.