Implementation of JavaScript dependency Injection

Source: Internet
Author: User
Php Chinese Network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... 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 in 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.

Var services = {abc: 123, def: 456, ghi: 789}; // assume that some services have 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 list of parameters defined by func and assign values one by one. Then, through some mechanism (Activitor ?), Instantiate the func.

Solution:

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 does not seem to have 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:

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

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.

var params = getFuncParams(func);for (var i in params) {    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 parameter array. It will automatically assign values to the func parameter list during the call, meet my needs.

The code is roughly as follows:

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

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

4. Print and test it:

Complete code:

Var // assume that some Service services = {abc: 123, def: 456, ghi: 789} have been defined, // obtain the func parameter list (dependency List) getFuncParams = function (func) {var matches = func. toString (). match (/^ function \ s * [^ \ (] * \ (\ s * ([^ \)] *) \)/m); if (matches & matches. length> 1) return matches [1]. replace (/\ s + /,''). split (','); return [];}, // fill in the parameter (dependency) setFuncParams = function (params) according to the parameter list (dependency List) {for (var I in params) {params [I] = services [params [I];} return params ;}; // The activator function Activitor (func) {var obj = {}; func. apply (obj, setFuncParams (getFuncParams (func); return obj;} // define the new Servicefunction Service (abc, ghi) {this. write = function () {console. log (abc); console. log (ghi) ;}}// instantiate the Service and call the var service = Activitor (Service); 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: 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.