The world of computer programming is actually a process of constantly abstracting simple parts and organizing these abstractions. JavaScript is no exception. When we use JavaScript to write applications, do we all use code written by others, such as some famous open source libraries or frameworks. As our project grows, more and more modules we need to rely on become more and more important. At this time, how to effectively organize these modules has become a very important issue. Dependency injection solves the problem of how to effectively organize code dependent modules. You may have heard the term "dependency injection" in some frameworks or libraries, such as the famous front-end framework AngularJS. Dependency injection is one of the very important features. However, dependency injection is nothing new at all. It has existed in other programming languages such as PHP for a long time. At the same time, dependency injection is not as complicated as imagined. In this article, we will learn the concept of dependency injection in JavaScript and explain in a simple and easy way how to write "dependency injection style" code.
Goal Setting
Suppose we now have two modules. The first module is used to send Ajax requests, while the second module is used as a router.
var service = function() {
Return { name: 'Service' };
}
var router = function() {
Return { name: 'Router' };
}
At this time, we wrote a function that requires the use of the two modules mentioned above:
var doSomething = function(other) {
var s = service();
var r = router();
};
Here, in order to make our code more interesting, this parameter needs to receive a few more parameters. Of course, we can completely use the above code, but the above code is slightly less flexible from any aspect. What if the name of the module we need to use changes to ServiceXML or ServiceJSON? Or what if we want to use some fake modules for testing purposes. At this point, we can't just edit the function itself. So the first thing we need to do is pass the dependent module as a parameter to the function, the code is as follows:
var doSomething = function(service, router, other) {
var s = service();
var r = router();
};
In the above code, we pass exactly the modules we need. But this brings up a new problem. Suppose we call the doSomething method in both parts of the code. At this point, what if we need a third dependency. At this time, it is not a wise idea to edit all the function call code. Therefore, we need a piece of code to help us do this. This is the problem that dependency injector tries to solve. Now we can set our goals:
1. We should be able to register dependencies
2. The dependency injector should receive a function and then return a function that can obtain the required resources
3. The code should not be complicated, but should be simple and friendly
4. The dependency injector should maintain the passed function scope
5. The passed function should be able to receive custom parameters, not just the described dependencies
requirejs/AMD method
Perhaps you have heard of the famous requirejs, which is a library that can solve dependency injection problems very well:
define(['service', 'router'], function(service, router) {
// ...
});
The idea of requirejs is that first we should describe the required modules, and then write your own functions. Among them, the order of parameters is important. Suppose we need to write a module called injector that can implement similar syntax.
var doSomething = injector.resolve(['service', 'router'], function(service, router, other) {
Expect(service().name).to.be('Service');
Expect(router().name).to.be('Router');
Expect(other).to.be('Other');
});
doSomething("Other");
Before proceeding, one thing that needs to be explained is that in the function body of doSomething, we use the expect.js assertion library to ensure the correctness of the code. There is something similar to the idea of TDD (Test Driven Development) here.
Now we officially start writing our injector module. First it should be a monolith so that it has the same functionality in every part of our application.
var injector = {
dependencies: {},
Register: function(key, value) {
This.dependencies[key] = value;
},
Resolve: function(deps, func, scope) {
}
}
This object is very simple, containing only two functions and a variable for storage purposes. What we need to do is check the deps array and then look for the answer in the dependencies variable. The remaining part is to use the .apply method to call the func variable we passed:
resolve: function(deps, func, scope) {
var args = [];
for(var i=0; i
if(this.dependencies[d]) {
args.push(this.dependencies[d]);
} else {
throw new Error('Can't resolve ' d);
}
}
Return function() {
func.apply(scope || {}, args.concat(Array.prototype.slice.call(arguments, 0)));
}
If you need to specify a scope, the above code can also run normally.
In the above code, the function of Array.prototype.slice.call(arguments, 0) is to convert the arguments variable into a real array. So far, our code passes the test perfectly. But the problem here is that we must write the required modules twice, and we cannot arrange them in any order. Extra parameters always come after all dependencies.
Reflection method
According to the explanation in Wikipedia, reflection means that an object can modify its own structure and behavior while the program is running. In JavaScript, simply speaking, it is the ability to read the source code of an object and analyze the source code. Still going back to our doSomething method, if you call the doSomething.toString() method, you can get the following string:
"function (service, router, other) {
var s = service();
var r = router();
}"
In this way, as long as we use this method, we can easily get the parameters we want, and more importantly, their names. This is also the method used by AngularJS to implement dependency injection. In the AngularJS code, we can see the following regular expression:
/^functions*[^(]*(s*([^)]*))/m
We can modify the resolve method to the code shown below:
resolve: function() {
var func, deps, scope, args = [], self = this;
func = arguments[0];
deps = func.toString().match(/^functions*[^(]*(s*([^)]*))/m)[1].replace(/ /g, '').split(' ,');
scope = arguments[1] || {};
Return function() {
var a = Array.prototype.slice.call(arguments, 0);
for(var i=0; i
var d = deps[i];
args.push(self.dependencies[d] && d != '' ? self.dependencies[d] : a.shift());
}
func.apply(scope || {}, args);
}
We use the above regular expression to match the function we defined, and we can get the following results:
["function (service, router, other)", "service, router, other"]
At this point, we only need the second item. But once we remove the extra spaces and split the string by , we get the deps array. The following code is the part we modified:
var a = Array.prototype.slice.call(arguments, 0);
...
args.push(self.dependencies[d] && d != '' ? self.dependencies[d] : a.shift());
In the above code, we traverse the dependent projects. If there are missing projects, if there are missing parts in the dependent projects, we get them from the arguments object. If an array is empty, using the shift method will simply return undefined without throwing an error. So far, the new version of the injector looks like this:
var doSomething = injector.resolve(function(service, other, router) {
Expect(service().name).to.be('Service');
Expect(router().name).to.be('Router');
Expect(other).to.be('Other');
});
doSomething("Other");
In the above code, we are free to mix up the order of dependencies.
But, nothing is perfect. There is a very serious problem with dependency injection of reflective methods. When code is simplified, errors occur. This is because during the code simplification process, the names of the parameters changed, which would cause the dependencies to fail to resolve. For example:
var doSomething=function(e,t,n){var r=e();var i=t()}
So we need the following solution, just like in AngularJS:
var doSomething = injector.resolve(['service', 'router', function(service, router) {
}]);
This is very similar to the AMD solution we saw at the beginning, so we can integrate the above two methods. The final code is as follows:
Copy code The code is as follows:
var injector = {
dependencies: {},
register: function(key, value) {
this.dependencies[key] = value;
},
resolve: function() {
var func, deps, scope, args = [], self = this;
if(typeof arguments[0] === 'string') {
func = arguments[1];
deps = arguments[0].replace(/ /g, '').split(',');
scope = arguments[2] || {};
} else {
func = arguments[0];
deps = func.toString().match(/^functions*[^(]*(s*([^)]*))/m)[1].replace(/ /g, '').split(',');
scope = arguments[1] || {};
}
return function() {
var a = Array.prototype.slice.call(arguments, 0);
for(var i=0; i
var d = deps[i];
args.push(self.dependencies[d] && d != '' ? self.dependencies[d] : a.shift());
}
func.apply(scope || {}, args);
}
}
}
这一个版本的resolve方法可以接受两个或者三个参数。下面是一段测试代码:
var doSomething = injector.resolve('router,,service', function(a, b, c) {
expect(a().name).to.be('Router');
expect(b).to.be('Other');
expect(c().name).to.be('Service');
});
doSomething("Other");
你可能注意到了两个逗号之间什么都没有,这并不是错误。这个空缺是留给Other这个参数的。这就是我们控制参数顺序的方法。
结语
在上面的内容中,我们介绍了几种JavaScript中依赖注入的方法,希望本文能够帮助你开始使用依赖注入这个技巧,并且写出依赖注入风格的代码。