Sooner or later you need to use other developers' abstractions - that is, you rely on other people's code. I'd love dependency-free (dependency-free) modules, but that's hard to achieve. Even those nice black box components you create rely on something more or less. This is where dependency injection comes into play. The ability to effectively manage dependencies is now an absolute necessity. This article summarizes my exploration of the problem and some of its solutions.
1. Goal
Imagine we have two modules. The first one is responsible for Ajax request service (service), and the second one is routing (router).
We need a tool that can help us do this. This is the problem that dependency injection tries to solve. Let’s write down some goals our dependency injection solution should achieve:
We should be able to register dependencies
1. Injection should take a function and return a function we need
2. We can’t write too much - we need to streamline and beautiful syntax
3 .Injection should maintain the scope of the passed function
4. The passed function should be able to accept custom parameters, not just dependency descriptions
5. It’s a perfect checklist, let’s implement it.
3. RequireJS/AMD method
You may have heard of RequireJS, it is a good choice to solve dependency injection.
}
}
However, this approach is not perfect, which is a very big problem with reflex type injections. Compression will break our logic because it changes the parameter names and we won't be able to maintain the correct mapping. For example, doSometing() might look like this when compressed:
var doSomething = injector.resolve(['service', 'router', function(service, router) {
}]);
5. Directly inject Scope
Sometimes I use the third injection variable, which involves the scope of the operating function (in other words, the this object). Therefore, many times there is no need to use this variable.