Implementation of JavaScript dependency Injection

Source: Internet
Author: User

Implementation of JavaScript dependency Injection

Today, various frameworks are modularized, and front-end javascript is no exception. Each module is responsible for certain functions, and modules are mutually dependent. The question is: how to implement javascript dependency injection? Javascript dependency injection is implemented by various frameworks. Here, we only learn how to implement it)

The following requirements:

Assume that the Key-Value set of the defined service module has been defined, func is the added service, and the parameter list is the service dependency.

  1. Var services = {abc: 123, def: 456, ghi: 789}; // assume that some services have been defined.
  2. Function Service (abc, ghi ){
  3. This. write = function (){
  4. Console. log (abc );
  5. Console. log (ghi );
  6. }
  7. }
  8. Function Activitor (func ){
  9. Var obj;
  10. // Implementation
  11. Return obj;
  12. }


Reflection Through some mechanism ?), Take out the list of parameters defined by func and assign values one by one. Then Activitor ?), Instantiate the func.


1. Obtain the func parameter list:

How can I obtain the parameter list? The first thing I think of is the reflection mechanism. Is there any reflection in javascript? I only know how to use the eval (str) function at present, but it seems that I have not obtained the implementation of the parameter list. In the definition of func. arguments, this attribute is valid only when func is called and parameters are passed.

Can you obtain the parameter list by processing the string after func. toString?

Try it out:

  1. function getFuncParams(func) { 
  2.      var matches = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m); 
  3.      if (matches && matches.length > 1) 
  4.          return matches[1].replace(/\s*/, '').split(','); 
  5.      return []; 
  6. }; 

Now, the list of func parameters is obtained.

2. Search for dependencies Based on the parameter list:

After obtaining the parameter list, you can get the dependency list. It is easy to pass in the dependency as a parameter.

  1. var params = getFuncParams(func); 
  2. or (var i in params) { 
  3.     params[i] = services[params[i]]; 

3. Pass the dependency parameters and instantiate them:

We know that javascript contains func. constructor and call (thisArg, [arg [, arg, [arg, […]). And apply (thisArg, args ...) Both functions can implement the instantiate func operation. The first parameter of the call function is the this pointer, and the remainder is the parameter list. this parameter is suitable for use when the list of known func parameters does not meet my needs. Let's look at the second apply function. The first parameter is also the this pointer, and the second parameter is the number of parameters group. It will automatically assign values to the func parameter list during the call, meet my needs.

The code is roughly as follows:

  1. function Activitor(func){ 
  2.     var obj = {}; 
  3.     func.apply(obj, params); 
  4.     return obj; 

Now we can create the func instance and pass the parameters required by the func.

4. Print and test it:

Complete code:

  1. Var
  2. // Assume that some services have been defined
  3. Services = {abc: 123, def: 456, ghi: 789 },
  5. // Obtain the func parameter list (dependency List)
  6. GetFuncParams = function (func ){
  7. Var matches = func. toString (). match (/^ function \ s * [^ \ (] * \ (\ s * ([^ \)] *) \)/m );
  8. If (matches & matches. length> 1)
  9. Return matches [1]. replace (/\ s +/, ''). split (',');
  10. Return [];
  11. },
  13. // Fill in parameters (dependencies) based on the parameter list (dependency List)
  14. SetFuncParams = function (params ){
  15. For (var I in params ){
  16. Params [I] = services [params [I];
  17. }
  18. Return params;
  19. };
  21. // Activator
  22. Function Activitor (func ){
  23. Var obj = {};
  24. Func. apply (obj, setFuncParams (getFuncParams (func )));
  25. Return obj;
  26. }
  28. // Define a new Service
  29. Function Service (abc, ghi ){
  30. This. write = function (){
  31. Console. log (abc );
  32. Console. log (ghi );
  33. }
  34. }
  36. // Instantiate the Service and call the Method
  37. Var service = Activitor (Service );
  38. Service. write ();

The console is successfully printed!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.