Create a module loading system similar to NodeJS with pure Javascript

Source: Internet
Author: User
The node. js module system has two important features: 1. variables defined by var in the module only apply to the current module, rather than the global one. 2. The require and module global variables can be used in each module. They are enclosed in quotation marks because they are actually provided by every module... SyntaxHighlighter. all ();

 

The node. js module system has two important features:

 

1. variables defined using var in a module only apply to the current module, rather than the global one.

 

2. You can use the "require" and "module" global variables in each module ". The reason for quotation marks is that they are actually common instances of each module, and instances in different modules are different.

 

You may think that these two features are different from the Javascript nature we use in the browser. They must be the native feature provided by the node. js runtime environment. Although we have not studied how NodeJS is implemented, we can use pure Javascript to make the same module system. In fact, we only need to use a syntax rarely used in Javascript: new Function ().

 

 

 

In Javascript, in addition to defining a function using Function func () {}, you can also use new function () to create a Function. Function is the prototype of all functions in Javascript, that is, the base class of all functions. Adding attributes to Function. prototype can add attributes to all Function instances. This is a common practice. Today, we will introduce how to create a Function by directly using new Function (). Although this is considered to be of poor performance, some useful functions can be achieved in some special scenarios.

 

 

The detailed syntax format of new Function () is:

 

 

New Function (args, body)

Here, args is a string that represents the function parameters. parameters are separated by commas, while the body is the function body itself. For example:

Var add = new Function ('x, y', 'Return x + y ;');

The created function is equivalent:

 

Var add = function (x, y ){

Return x + y;

}

There is no difference between the two effects. We usually only use the second method because it has better readability.

 

 

Now let's look at two potential application scenarios of new Function:

1. avoid naming conflicts

As you know, the Javascript file introduced by the script label is global, and the variables defined in each file are global. To avoid naming conflicts, you can use the following tips:

 

(Function (){

Var x = 0;

// My code

})();

By outsourcing a function and calling it immediately, you can create a closure. The scope of the variable is limited to the function body. This avoids naming conflicts with other files. However, in some cases, we need to use a third-party Javascript file or a file that cannot be modified for some reason to complete an independent task, but some global variables are defined. These files cannot be modified to use the methods mentioned above to avoid name conflicts. Now our new Function () can play a role. At this time, we did not introduce Javascript files through script, but obtained the content of the Javascript file through XMLHttpRequest, and then executed the Javascript in the following way:

 

Var result = (new Function ('', jsCode + '; return {x: x }'))();

In this way, we also wrap a layer of functions outside the jsCode, and return the expected results as return values for external programs to use. Of course, for most independent files, we do not necessarily need to return values, but just need to execute it. Next, let's look at the next application scenario.

 

 

2. Build your own module Loading System

This is also an extension of the previous application scenario. Since we load Javascript files in this way, why not make it into a general module Loading System for your project to use. Therefore, you do not need to outsource a function to every file to avoid name conflicts. In fact, if you use NodeJS, you may know that the variables defined in each module in NodeJS are limited to the current module and will not be directly used by other modules. In addition, each module has a default require and module variable. Both modules can be used as global variables, but they are not global variables, the node. js documentation clearly states that they are different instances in each module. In this way, the modifications made by one module do not affect other modules. You may think that this must be a special feature provided by the native environment of NodeJS, but in fact, we can use pure Javascript to create the same module mechanism, you only need to make some modifications to the example above. For example, this loader has the following code:

 

Var require = getRequireInstance ();

Var module = getModuleInstance ();

// Get the code of the Javascript file to be loaded through XMLHttpRequest

Var moduleText = getModuleText ();

// Execute the module code and "inject" require and module variables.

(New Function ('require, module', moduleText) (require, module );

How about it, isn't it easy? Although new Function () is a rarely used Function, it is indeed very flexible. More application scenarios rely on everyone to continue mining.

 

From the Chinese blog of Dojo-

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.