[JavaScript] JavaScript advanced series-use require to efficiently organize code structures

Source: Internet
Author: User

Preface

In actual projects, Javascript development faces a big problem, that is, poor code controllability. As the project progresses, the amount of JavaScript code may explode. If you do not control it, the potential problems will increase. In this case, many people think that JavaScript is a simple scripting language that can be used in an in-depth understanding. This is also why many domestic projects, JavaScript, are messy, and security scalability is poor. In fact, JavaScript is really not simple.

 

Use require to manage code structures

The require code is as follows:

1 var require, define;
2 (function (){
3 var modules = {};
4
5 function build (module ){
6 var factory = module. factory;
7 module. Exports = {};
8 delete module. factory;
9 Factory (require, module. Exports, module );
10 return module. Exports;
11}
12
13 require = function (ID ){
14 if (! Modules [ID]) {
15 throw 'module' + ID + 'not found ';
16}
17 return modules [ID]. Factory? Build (modules [ID]): modules [ID]. Exports;
18 };
19
20 define = function (ID, factory ){
21 if (modules [ID]) {
22 throw 'module' + ID + 'already defined ';
23}
24
25 modules [ID] = {
26 ID: ID,
27 Factory: Factory
28 };
29 };
30
31 define. Remove = function (ID ){
32 Delete modules [ID];
33}
34
35 })();

No matter whether you believe it or not, just 35 lines of code can help you manage your code. Next we will explain this code in detail,

1. Row 1st defines two global variables: require and define.

Define: defines the code module. It is like a class in Java that encapsulates methods and attributes. The defined code module encapsulates the methods and attributes of some columns for calling.

Require: Used to call encapsulated code modules. Like java in a class, you can call attributes and methods of another class. Require is used to create an object of a module, for other modules to call the methods and attributes in it.

2. 2nd ~ Line 35 details the logic of the define, require, and define. Remove methods.

3. Row 3rd defines a local variable modules, which is used to cache all modules defined.

4. Row 20th defines the define method. Here there are two parameter IDs and factory,

ID: the type of this parameter is string. It is used to define the organizational structure of a module and must be unique. You can define it as "cnblogs/utils" or "cnblogs/View ".

Factory: this parameter is of the function type and is used to define the code implementation of the module.

5. Row 31st defines the define. Remove method, which is used to delete a module.

13th rows define the require method, which is used to load a module

7. the second line defines the private method build. The first time you look at this method, you will find it strange. The factory and exports in it will make you feel confused. I will give a brief introduction first, factory is the parameter factory in the define method. exports can be understood as the API to be shared here.

Let's take an example to better understand this.

1 Define ('cnblogs/utils ', function (require, exports, module ){
2 var utils = exports;
3
4 utils. isarray = function (){
5 return object. Prototype. tostring. Call (A) = '[object array]';
6 };
7
8 utils. Alert = function (MSG ){
9 If (alert ){
10 alert (MSG );
11} else if (console & console. Log ){
12 console. Log (MSG );
13}
14 };
15 });
16
17 define ('cnblogs/view', function (require, exports, module ){
18 var utils = require ('cnblogs/utils ');
19 var views = {
20 showwebview: function (){
21 utils. Alert ('show webview ...');
22 },
23 hidewebview: function (){
24 utils. Alert ('hide webview ...');
25}
26 };
27 module. Exports = views;
28 });
29
30 var cnblogsview = require ('cnblogs/view ');
31 cnblogsview. showwebview ();
32
33 /*
34 define. Remove ('cnblogs/view ');
35 var cnblogsview1 = require ('cnblogs/view ');
36 cnblogsview1.showwebview ();
37 */

Note:

In this example, we create two modules: "cnblogs/utils" and "cnblogs/View ". "Cnblogs/utils" is used to define a tool method in a project. This module is similar to the tool class in Java. "Cnblogs/View" is used to define public methods related to views in the project, and the "alert" method in the "cnblogs/utils" module is called in this module.

Explanation:

1. 1st ~ Use the define method to define the "cnblogs/utils" module in lines 15, 2nd ~ The 14 rows are the content of the function body of the factory parameter of the define method. The factory function defines three parameters.

Require: The global variable require.

Exports: object type, used to encapsulate methods and attributes to be shared

Module: a reference of the module.

Row 2nd var utils = exports; indicates that the utils object will be exports, for example, row 18th, VAR utils = require ('cnblogs/utils '); this utils is the exports object, that is, the utils object in row 2nd.

2. 17th ~ The 28 rows define the "cnblogs/View" module. Here we will focus on the 18th and 27th rows. The 18th rows use the require method to obtain the "cnblogs/utils" module information and the 27th rows module. exports = views; equivalent to using VAR views = exports;

3. 30th ~ 37 rows are used for testing.

 

Author information:

QQ: 1321518080

Email: hucaijun520. OK @163.com

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.