Home Web Front-end JS Tutorial Sharing ideas for implementing dependency injection in JavaScript_javascript skills

Sharing ideas for implementing dependency injection in JavaScript_javascript skills

May 16, 2016 pm 04:19 PM
javascript dependency injection

Nowadays, every framework is being modularized, even front-end javascript is no exception. Each module is responsible for certain functions, and there are interdependencies between modules. So the question arises: How to implement dependency injection in JavaScript? (Dependency injection of JavaScript has corresponding implementations in all major frameworks. Here we only learn the implementation ideas)

The following requirements:

Assume that there is already a defined service module Key-Value set, func is the new service added, and the parameter list is the service dependency.

Copy code The code is as follows:

var services = { abc : 123, def : 456, ghi : 789 }; // Assume that some Service
has been defined function Service(abc, ghi){
This.write = function(){
console.log(abc);
console.log(ghi);
}
}
function Activitor(func){
var obj;
// Implement
Return obj;
}

Solution:

Through some mechanism (reflection?), take out the parameter list defined by the func and assign values ​​one by one. Then instantiate the func through some mechanism (Activitor?).

Solution:

1. Get the parameter list of func:

How to get the parameter list? The first thing that comes to my mind is the reflection mechanism. So is there reflection in javascript? There should be. Currently, I only know how to use the eval(str) function, but it seems that there is no relevant implementation for obtaining the parameter list. Looking at the func.arguments definition again, this property is only valid when func is called and parameters are passed, and it cannot meet the requirements.

Can we get the parameter list by processing the string after func.toString()?

Get started and try it:

Copy code The code is as follows:

function getFuncParams(func) {
var matches = func.toString().match(/^functions*[^(]*(s*([^)]*))/m);
If (matches && matches.length > 1)
            return matches[1].replace(/s*/, '').split(',');
Return [];
};

At this point, the func parameter list array is obtained.

2. Find dependencies based on the parameter list:

After getting the parameter list, that is, getting the dependency list, it is very simple to pass in the dependencies as parameters.

Copy code The code is as follows:

var params = getFuncParams(func);
for (var i in params) {
params[i] = services[params[i]];
}

3. Pass dependency parameters and instantiate:

We know that there are two functions called func.constructor in javascript: call(thisArg,[arg[,arg,[arg,[…]]]]) and apply(thisArg,args…), both of which can be instantiated. func operation. The first parameter of the call function is this pointer, and the rest is the parameter list. This is suitable for use when the func parameter list is known, but does not meet my needs. Looking at the second apply function, the first parameter is also this pointer, and the second parameter is the parameter array. When it is called, it will automatically assign values ​​to the parameter list of func one by one, which just meets my needs.

The code is roughly as follows:

Copy code The code is as follows:

function Activitor(func){
var obj = {};
func.apply(obj, params);
Return obj;
}

At this point we can create an instance of the func and pass the parameters required by the func.

4. Print and test:

Full code:

Copy code The code is as follows:

var
// Assume that some Service
has been defined Services = { abc: 123, def: 456, ghi: 789 },

// Get the parameter list of func (dependency list)
GetFuncParams = function (func) {
         var matches = func.toString().match(/^functions*[^(]*(s*([^)]*))/m);
If (matches && matches.length > 1)
                 return matches[1].replace(/s /, '').split(',');
         return [];
},

// Fill in parameters (dependencies) based on parameter list (dependency list)
setFuncParams = function (params) {
for (var i in params) {
              params[i] = services[params[i]];
}
         return params;
};

// Activator
function Activitor(func) {
var obj = {};
func.apply(obj, setFuncParams(getFuncParams(func)));
Return obj;
}

//Define new Service
function Service(abc, ghi) {
This.write = function () {
console.log(abc);
console.log(ghi);
}
}

// Instantiate Service and call method
var service = Activitor(Service);
service.write();


The console prints successfully!
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Dependency injection pattern in Golang function parameter passing Dependency injection pattern in Golang function parameter passing Apr 14, 2024 am 10:15 AM

In Go, the dependency injection (DI) mode is implemented through function parameter passing, including value passing and pointer passing. In the DI pattern, dependencies are usually passed as pointers to improve decoupling, reduce lock contention, and support testability. By using pointers, the function is decoupled from the concrete implementation because it only depends on the interface type. Pointer passing also reduces the overhead of passing large objects, thereby reducing lock contention. Additionally, DI pattern makes it easy to write unit tests for functions using DI pattern since dependencies can be easily mocked.

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles