Detailed description of Javascript Modular programming and javascript Modularization

Source: Internet
Author: User

Detailed description of Javascript Modular programming and javascript Modularization

Modular programming is a very common Javascript programming mode. Generally, it makes the code easier to understand, but there are many good practices that are not widely known.

Basic

First, let's give a brief overview of some modular models that Eric Miraglia (YUI Developer) described three years ago when he first published a blog describing the modular model. If you are already familiar with these modular models, you can skip this section and start with "advanced mode.

Anonymous Closure

This is a basic structure that makes everything possible, and it is also the best feature of Javascript. We will simply create an anonymous function and execute it immediately. All code will run in this function and survive in a closure that provides privatization, which is sufficient to allow the variables in these closures to run throughout the entire lifecycle of our application.

Copy codeThe Code is as follows:
(Function (){
//... All vars and functions are in this scope only
// Still maintains access to all globals
}());

Note that this pair contains the outermost parentheses of the anonymous function. Because of the language features of Javascript, this pair of parentheses is required. In js, statements starting with the keyword function are always considered as function declarative statements. Wrap this code in parentheses to let the interpreter know that this is a function expression.

Import global variables

Javascript has a feature called implicit global variables. No matter where a variable name is used, the interpreter will reverse find the var declaration statement for this variable based on the scope chain. If the var declaration statement is not found, this variable is considered a global variable. If this variable is used in a value assignment statement and does not exist, a global variable is created. This means that it is easy to use or create global variables in anonymous closures. Unfortunately, this will make the written code extremely difficult to maintain, because for people's intuitive feelings, they cannot tell at a glance those are global variables.

Fortunately, our anonymous functions provide simple alternatives. By passing global variables as parameters to our anonymous functions, we can get code that is clearer and faster than implicit global variables. The following is an example:

Copy codeThe Code is as follows:
(Function ($, YAHOO ){
// Now have access to globals jQuery (as $) and YAHOO in this code
} (JQuery, YAHOO ));

Module Export

Sometimes you not only want to use global variables, but also declare them for repeated use. We can easily do this by exporting them-by returning values from anonymous functions. In this way, a basic prototype of modular mode will be completed. The following is a complete example:

Copy codeThe Code is as follows:
Var MODULE = (function (){
Var my = {},
PrivateVariable = 1;
Function privateMethod (){
//...
}
My. moduleProperty = 1;
My. moduleMethod = function (){
//...
};
Return my;
}());

Note that we have declared a global MODULE called MODULE, which has two public attributes: a method called MODULE. moduleMethod and a variable named MODULE. moduleProperty. In addition, it maintains a private built-in State that uses the closure of anonymous functions. At the same time, we can easily import the required global variables and use this modular mode as we have learned before.

Advanced Mode

The basis described in the above section is sufficient to deal with many situations. Now we can further develop this modular model to create more powerful and scalable structures. Let's start with the MODULE and introduce these advanced models one by one.

Zoom in Mode

The entire module must be modular in a file. Anyone involved in a large project will understand the value of splitting multiple files in js. Fortunately, we have a great implementation to enlarge the module. First, import a module, add attributes for it, and then export it. The following is an example -- enlarge it from the original MODULE:

Copy codeThe Code is as follows:
Var MODULE = (function (my ){
My. anotherMethod = function (){
// Added method...
};
Return my;
} (MODULE ));

We use the var keyword to ensure consistency, although it is not necessary here. After this code is executed, our MODULE has a new public method called MODULE. anotherMethod. This enlarged file also maintains its own private built-in status and imported objects.

Zoom-in Mode

The above example requires that our initialization module be executed first, and then amplified to execute the module. Of course, sometimes this may not be necessary. One of the best things Javascript applications can do to improve performance is to execute scripts asynchronously. We can create flexible multi-part modules and enable them to be loaded in any order through the wide zoom mode. Each file needs to be organized according to the following structure:

Copy codeThe Code is as follows:
Var MODULE = (function (my ){
// Add capabilities...
Return my;
} (MODULE | {}));

In this mode, the var expression is required. Note that if the MODULE has not been initialized, this Import Statement will create a MODULE. This means that you can use a tool like LABjs to concurrently load all your module files without being blocked.

Zoom-in Mode

The wide amplification mode is very good, but it will also impose some restrictions on your module. Most importantly, you cannot safely overwrite the attributes of a module. You cannot use attributes in other files during initialization (but you can use them during running ). The zoom-in mode contains a loaded sequence and allows the attribute to be overwritten. Here is a simple example (to enlarge our original MODULE ):

Copy codeThe Code is as follows:
Var MODULE = (function (my ){
Var old_moduleMethod = my. moduleMethod;
My. moduleMethod = function (){
// Method override, has access to old through old_moduleMethod...
};
Return my;
} (MODULE ));

The preceding example overwrites the implementation of MODULE. moduleMethod, but you can maintain a reference to the original method when necessary.

Cloning and inheritance

Copy codeThe Code is as follows:
Var MODULE_TWO = (function (old ){
Var my = {},
Key;
For (key in old ){
If (old. hasOwnProperty (key )){
My [key] = old [key];
}
}
Var super_moduleMethod = old. moduleMethod;
My. moduleMethod = function (){
// Override method on the clone, access to super through super_moduleMethod
};
Return my;
} (MODULE ));

This mode may be the most inflexible option. It does make the Code look neat, but it is at the cost of flexibility. As in the code above, if an attribute is an object or function, it will not be copied, but will become the second reference of this object or function. If one of them is modified, the other will be modified at the same time !). This problem can be solved through recursive cloning, but function cloning may not be able to solve it. Maybe eval can solve it. Therefore, the method I described in this article only takes into account the integrity of the article.

Private variable across files

Dividing a module into multiple files has a major restriction: each file maintains its own private variables and cannot access the private variables of other files. However, this problem can be solved. Here is an example of a wide amplification module that maintains private variables across files:

Copy codeThe Code is as follows:
Var MODULE = (function (my ){
Var _ private = my. _ private = my. _ private | | {},
_ Seal = my. _ seal = my. _ seal | function (){
Delete my. _ private;
Delete my. _ seal;
Delete my. _ unseal;
},
_ Unseal = my. _ unseal = my. _ unseal | function (){
My. _ private = _ private;
My. _ seal = _ seal;
My. _ unseal = _ unseal;
};
// Permanent access to _ private, _ seal, and _ unseal
Return my;
} (MODULE | {}));

All files can be set on their own _ private variables, and it can be accessed by other files. Once the MODULE is loaded, the application can call MODULE. _ seal () to prevent external calls to internal _ private. If this module needs to be zoomed in again, the internal method in any file can call _ unseal () before loading the new file (), and call _ seal () again after the new file is executed (). I am using this mode at work today, and I have never seen this method elsewhere. I think this is a very useful mode and it is worth writing an article on this mode.

Sub-module

Our last advanced mode is obvious and simple. Creating sub-modules has many excellent instances. This is like creating a common module:

Copy codeThe Code is as follows:
MODULE. sub = (function (){
Var my = {};
//...
Return my;
}());

Although this seems simple, I think it is worth mentioning here. The sub-module has the advanced advantages of all general modules, including the amplification mode and privatization status.

Conclusion

Most advanced modes can be combined to create a more useful mode. If I really want to recommend a modular mode for designing complex applications, I will choose to combine the wide amplification mode, private variables and sub-modules.

I have not considered the performance of these models, but I would rather convert this into a simpler way of thinking: If a modular model has good performance, it can minimize the workload and make it faster to download the script file. The wide zoom-in mode allows simple non-blocking parallel downloads, which speeds up the download. The initialization time may be slightly slower than other methods, but it is worthwhile to weigh the advantages and disadvantages. As long as the global variables are imported accurately, the runtime performance will not be affected. In addition, it is possible that private variables can be used to shorten the reference chain in the sub-module to achieve faster running speed.

Here is an example of a sub-module dynamically loading itself into its parent module (if the parent module does not exist, it is created ). For simplicity, I remove private variables. Of course, it is very easy to add private variables. This programming mode allows an entire complex hierarchical code library to be loaded in parallel through sub-modules.

Copy codeThe Code is as follows:
Var UTIL = (function (parent, $ ){
Var my = parent. ajax = parent. ajax || {};
My. get = function (url, params, callback ){
// OK, so I'm cheating a bit :)
Return $. getJSON (url, params, callback );
};
// Etc...
Return parent;
} (UTIL | {}, jQuery ));

This article summarizes the current best practices of "Javascript Modular programming" and explains how to put it into practice. Although this is not a preliminary tutorial, you only need to understand the basic syntax of Javascript.

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.