search
HomeWeb Front-endJS TutorialDetailed explanation of dependency injection in JavaScript_javascript skills

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.

Copy code The code is as follows:

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:
Copy code The code is as follows:

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:
Copy code 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:

Copy code The code is as follows:

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.
Copy code The code is as follows:

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.

Copy code The code is as follows:

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:
Copy code The code is as follows:

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:


Copy code The code is as follows:
"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:

Copy code The code is as follows:
/^functions*[^(]*(s*([^)]*))/m


We can modify the resolve method to the code shown below:

Copy code The code is as follows:

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:


Copy code The code is as follows:
["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:

Copy code The code is as follows:
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:


Copy code The code is as follows:
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:


Copy code The code is as follows:
var doSomething=function(e,t,n){var r=e();var i=t()}

So we need the following solution, just like in AngularJS:

Copy code The code is as follows:
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中依赖注入的方法,希望本文能够帮助你开始使用依赖注入这个技巧,并且写出依赖注入风格的代码。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),