javascript--Dependency Injection

Source: Internet
Author: User

I learned sparse, this article only for the introduction, Welcome to the road Daniel come to treatise, greatly appreciated!

Now the frameworks are modular, and even the front-end JavaScript is no exception. Each module is responsible for a certain function, and the modules and modules are interdependent, so the question is: How does JavaScript's dependency injection be implemented? (JavaScript relies on injection, each big frame has the corresponding realization, here only learns realizes the idea)

The following requirements:

Suppose there is already a defined service Module Key-value collection, Func is the new service added, and the parameter list is a service dependency.

1 varServices = {abc:123, def:456, ghi:789};//Assuming that some service has been defined.2 functionService (ABC, GHI) {3      This. Write =function(){4 Console.log (ABC);5 Console.log (GHI);6     }7 }8 functionActivitor (func) {9     varobj;Ten     //Implement One     returnobj; A}

Solution Ideas:

Through some kind of mechanism (reflection?) ), remove the parameter list defined by the Func and assign each value. And then through some kind of mechanism (activitor? ) to instantiate the Func.

Solution:

One, get the parameter list of func:

How do I get a list of parameters? The first thing I think about is the reflection mechanism. Is there any reflection in the JavaScript? There should be, I only know to use the Eval (str) function, but it doesn't seem to get the relevant implementation of the parameter list. Looking at the func.arguments definition, this property is only valid when calling Func and passing parameters, and does not satisfy the requirements.

Can you get the argument list by processing the string after func.tostring ()?

Try it:

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 };

This gets the func parameter list array.

Second, according to the parameter list to find dependencies:

Given a list of parameters, it is easy to get a dependency list and pass in a dependency as a parameter.

1 var params = getfuncparams (func); 2  for (var in params) {3     params[i] = services[params[i]]; 4 }

Third, pass the dependency parameter and instantiate:

We know that there are func.constructor in JavaScript with call (thisarg,[arg[,arg,[arg,[...]]) and apply (Thisarg,args ...) Two functions, all of which can instantiate the Func operation. Where the first parameter of the call function is the this pointer, the remainder is the argument list, which is suitable for use in cases where the Func parameter list is known, and does not meet my needs. Look at the second apply function, the first parameter is the this pointer, the second parameter is an array of parameters, which is automatically assigned to the Func parameter list one by one when called, just to meet my needs.

The code might look like this:

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

we are now able to create the func instance, and pass the func the required parameters.

Four, print test it:

Full code:

1 var2     //Assuming that some service has been defined.3Services = {abc:123, def:456, ghi:789 },4 5     //gets the argument list for Func (dependency list)6Getfuncparams =function(func) {7         varmatches = Func.tostring (). Match (/^function\s*[^\ (]*\ (\s* ([^\)]*) \)/m);8         if(Matches && matches.length > 1)9             returnMatches[1].replace (/\s+/, '). Split (', '));Ten         return []; One     }, A  -     //populating parameters (dependencies) based on the parameter list (dependency list) -Setfuncparams =function(params) { the          for(varIinchparams) { -Params[i] =Services[params[i]]; -         } -         returnparams; +     }; -  + //Activating device A functionActivitor (func) { at     varobj = {}; - func.apply (obj, Setfuncparams (Getfuncparams (func))); -     returnobj; - } -  - //Define new service in functionService (ABC, GHI) { -      This. Write =function () { to Console.log (ABC); + Console.log (GHI); -     } the } *  $ //instantiate the service and invoke the methodPanax Notoginseng varService =Activitor (Service); -Service.write ();

The console prints successfully!

javascript--Dependency Injection

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: info-contact@alibabacloud.com 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.