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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.