How JavaScript modules are written

Source: Internet
Author: User
Tags jquery library

JavaScript is not a modular programming language, it does not support the class, not to mention the module. (The ECMAScript standard Sixth Edition, which is under development, will officially support "Class" and "module", but it still takes a long time to put into practice.) )

First, the original wording

A module is a set of methods for implementing a specific function.

Simply put the different functions (and the variables that record the state) together, even if it is a module.

function M1 () {
//...
}

function m2 () {
//...
}

The above functions M1 () and M2 () to form a module. When used, call directly on the line.

The disadvantage of this approach is obvious: "Pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship.

Ii. the wording of the object

In order to solve the above shortcomings, the module can be written as an object, all the module members are placed in this object.

var module1 = new Object ({

_count:0,

M1:function () {
//...
},

M2:function () {
//...
}

});

The above functions M1 () and M2 () are encapsulated in the Module1 object. When used, it is called the property of the object.

MODULE1.M1 ();

However, such a notation exposes all module members, and the internal state can be overridden externally. For example, external code can directly change the value of an internal counter.

Module1._count = 5;

Iii. immediate execution of function notation

Using the Execute functions now (immediately-invoked function Expression,iife), you can achieve the purpose of not exposing private members.

var Module1 = (function () {

var _count = 0;

var m1 = function () {
//...
};

var m2 = function () {
//...
};

return {
M1:M1,
M2:m2
};

})();

Using the notation above, the external code cannot read the internal _count variable.

Console.info (Module1._count); Undefined

Module1 is the basic way of writing JavaScript modules. The following, and then processing the writing.

Four, amplification mode

If a module is large and must be divided into several parts, or if one module needs to inherit another module, then it is necessary to use "magnification mode" (augmentation).

var Module1 = (function (mod) {

MOD.M3 = function () {
//...
};

return mod;

}) (Module1);

The code above adds a new method M3 () to the Module1 module and then returns the new Module1 module.

Five, wide magnification mode (Loose augmentation)

In a browser environment, parts of the module are usually obtained from the web, and sometimes it is not possible to know which part is loaded first. If you use the previous section, the first part of the execution is likely to load a nonexistent empty object, then use the "wide magnification mode".

var Module1 = (function (mod) {

//...

return mod;

}) (Window.module1 | | {});

In contrast to Loupe mode, the wide magnification mode is a parameter that executes function immediately, which can be an empty object.

VI. Input Global Variables

Independence is an important feature of the module and it is best not to interact directly with other parts of the program.

In order to call global variables inside a module, you must explicitly enter other variables into the module.

var Module1 = (function ($, YAHOO) {

//...

}) (JQuery, YAHOO);

The above Module1 module needs to use the jquery library and Yui Library, the two libraries (actually two modules) as a parameter input module1. In addition to ensuring the independence of the module, it also makes the dependency between modules obvious. For more discussion on this, see Ben Cherry's famous article, "JavaScript Module pattern:in-depth."

VII. Specification of modules

First think about why the module is important?

Because of the module, we can more easily use other people's code, want what function, load what module.

However, this has a premise, that is, we must write the module in the same way, otherwise you have your writing, I have my writing, it is not messy set! This is even more important considering that the JavaScript module does not yet have an official specification.

Currently, there are two types of JavaScript module specifications available: Commonjs and AMD. I mainly introduce AMD, but start with Commonjs.

Eight, CommonJS

In 2009, American programmer Ryan Dahl created the node. JS project to use the JavaScript language for server-side programming.

This symbol "JavaScript modular programming" was formally born. Because frankly speaking, in the browser environment, no module is not particularly big problem, after all, the complexity of the Web-page program is limited, but on the server side, must have modules, and the operating system and other applications to interact with, otherwise it is impossible to program.

Node. JS's module system is implemented with reference to the COMMONJS specification. In Commonjs, there is a global method require () that is used to load the module. Assuming that a mathematical module is math.js, it can be loaded as follows.

var math = require (' math ');

Then, you can invoke the method provided by the module:

var math = require (' math ');

Math.add (2,3); 5

Since this series is primarily for browser programming and does not involve node. js, there is no more introduction to COMMONJS. As long as we know here, require () is used to load the module on the line.

Nine, the browser environment

With the server-side module, it is natural for everyone to want the client module. And it is best to be compatible, a module without modification, both server and browser can be run.

However, due to a significant limitation, the COMMONJS specification does not apply to the browser environment. or the previous section of the code, if run in the browser, there will be a big problem, you can see it?

var math = require (' math ');

Math.add (2, 3);

The second line, Math.add (2, 3), runs after the first line of require (' math '), so it must wait until the math.js load is complete. That is, if the load time is long, the entire application will stop there and so on.

This is not a problem on the server side, because all the modules are stored on the local hard disk, can be loaded synchronously, waiting time is the hard disk read time. However, for the browser, this is a big problem, because the modules are placed on the server side, the waiting time depends on the speed of the network, it may take a long time, the browser is in "Suspended animation" status.

As a result, the browser-side module cannot be "synchronous-loaded" (synchronous) and can only take "asynchronous load" (asynchronous). This is the background to the birth of the AMD specification.

X. AMD

AMD is the abbreviation for "Asynchronous module definition", meaning "async module definition". It loads the module asynchronously, and the module's load does not affect the execution 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.

AMD also uses the Require () statement to load the module, but unlike COMMONJS, it requires two parameters:

Require ([module], callback);

The first parameter, [module], is an array in which the member is the module to be loaded, and the second parameter, callback, is the callback function after the load succeeds. If you rewrite the previous code in AMD form, this is the following:

Require ([' math '], function (math) {

Math.add (2, 3);

});

Math.add () is not synchronized with the math module, and the browser does not take place in animation. So it's clear that AMD is better suited for a browser environment.

Currently, there are two main JavaScript libraries that implement the AMD specification: Require.js and Curl.js.

How JavaScript modules are written

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.