I'm studying Dependency Injection in JavaScript. I've learned what I need to accomplish, according to Wikipedia,
The client delegates to external code (the injector) the responsibility of providing its dependencies. The client is not allowed to call the injector code.[2] It is the injecting code that constructs the services and calls the client to inject them. This means the client code does not need to know about the injecting code. The client does not need to know how to construct the services. The client does not need to know which actual services it is using. The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services.
But I'm not sure how this should be done in JavaScript. I could probably set out to create all sorts of ways to inject dependencies in JavaScript, matching "services" to "clients" in the code structure and technically satisfy the terms of the Dependency Inversion Principle. But that doesn't mean it would be the best/correct way.
For example lets say I have a wheel
(service) which every car
(client) needs, along with services: gasPedal
, break
, clutch
, and stick
.
- What should a proper dependency injector look like in JavaScript?
- How does one inject the dependency without calling on the injection code from the client?
Note: None of the answers so far cover doing this manually. I know I can use libraries to do it, what I'm asking about - the challenging aspect of injectors - is how to create them from scratch, what the structure of one would actually look like, not how to use a library which supports them.
I'm trying to learn what the function for an injector would be structured like for the sake of truly understanding dependency injection at its core - the function that implements injection. I'm not asking for a complete function or working code, just a good explanation or even an overly simplified pseudo-code example.
steer
towheel
since a service is defined as an object that does something, so the dependency would bewheel
and what it does would besteer()