Modular programming of JavaScript

Source: Internet
Author: User
Tags define function

At the beginning of the design, JavaScript did not provide a native, language-level, modular way to organize code, such as the Java language, which manages and uses modules through package and import. ECMAScript 6 introduces the concept of class and import to support modularity, but it still takes a long time for the browser to fully support this standard.

The modularity of an application is defined by a number of highly decoupled functional modules that are stored in different places. In recent years, with the complexity of JavaScript applications, large-scale, JavaScript code needs more orderly organization, in the JavaScript community there are many kinds of modular implementation, the main two specifications are COMMOMJS and AMD, this article will focus on these two specifications.

1. CommonJS

COMMONJS is a project designed to build JavaScript systems outside of the browser and is dedicated to the standardization of JavaScript modules. The main feature is the synchronous loading of the JavaScript module, running on the server side. node. JS is an implementation of the COMMONJS specification.

Commonjs the definition of the module is very simple, divided into module definition (exports), module reference (Require), module marked three parts.
Returns the object that the current module wants to supply to other modules through the global variable exports:

1 //Defining Behavior2 functionFoobar () {3          This. Foo =function(){4Console.log (' Hello foo '));5         }6 7          This. Bar =function(){8Console.log (' Hello bar ');9         }Ten } One //exposing the Foobar to other modules AExports.foobar = Foobar;

Import the output of other modules through the global function require:

1 // use files in the same directory as module files 2 var foobar = require ('./foobar '). Foobar,3new  foobar (); 4 // ' Hello bar '

The module is actually a parameter passed to the Require method, which specifies the path of the file to be loaded, without the suffix. js, for example, "./foobar" in the example above.

The code for the Commonjs module runs at the module scope, does not contaminate the global scope, and the module can be loaded multiple times, but the results are cached. COMMONJS is primarily designed for the server-side JavaScript runtime, which is loaded synchronously, making it difficult to run COMMONJS code in a browser. node. JS has some projects such as Browserify, commonjs into the browser, Browserify will rely on a separate JS file packaged into a separate JS file, unified loading to the browser side. 2. AMD

AMD (Asynchronous module definition) is designed for the browser environment, loading the module asynchronously, the load of the module does not affect the operation of the statement behind it. All statements that rely on this module are defined in a callback function that will not run until the load is complete.

The module is defined in the closure by the Define function, in the following format:

1 /* options available */ , 2        /* options available */ , 3        /* function used to initialize a module or object */);

The ID is the name of the module and it is an optional parameter. dependencies Specifies the list of modules to be relied upon, which is an array and an optional parameter, and the output of each dependent module is passed into the factory as a parameter at a time. Factory is the last parameter that wraps the concrete implementation of the module, which is a function or object. If it is a function, then its return value is the output interface or value of the module.

Define a module named MyModule, which relies on Foo, the bar module:

1Define (' MyModule ',2     //Dependent3[' foo ', ' Bar '],4     //Dependencies (foo and bar) are mapped as parameters of a function5     function(foo, bar) {6         //returns a value that defines the module export interface7         //Create a module here8         varMyModule = {9DoSomething:function(){Ten             } One         } A         returnMyModule; -});

Define a standalone module that does not need to rely on any other modules:

Define (function  () {    return  {        function() {}    };});

To invoke the module via require:

1 function (foo, bar) {2        foo.dosomething (); 3 });

You can also use require to load other modules inside the module definition:

1Definefunction(require) {2     varIsReady =false, Foobar;3 4Require ([' foo ', ' Bar '),function(foo, bar) {5IsReady =true;6Foobar = foo () +bar ();7     });8 9     return {Ten Isready:isready, One Foobar:foobar A     }; -});

In the above example, the IsReady property is false before Foo and bar do not load.

There are currently two JavaScript libraries that implement the AMD specification: Require.js and Curl.js. Requirejs was created by James Burke, who is also the founder of the AMD specification.

3. Conclusion

CommonJS uses a server-first strategy to load modules synchronously, and tries to cover more and broader things, such as file Io,promise and so on. AMD has taken a browser-first approach to developing and loading modules asynchronously. It supports objects, functions, constructors, strings, JSON, and many other types of modules that run in a browser-local environment.

Since the current version of JavaScript does not provide native modularity support, community developers have done a lot of modular exploration to make JavaScript engineering possible, COMMONJS and AMD are the main two specifications.

Modular programming of JavaScript

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.