JavaScript Modular programming (notes)

Source: Internet
Author: User

JavaScript Modular programming (notes)

I have always been familiar with JS. I recently encountered this problem, so I learned it online. I haven't fully understood it yet. I will post my notes first;

Chapter 1 JavaScript Modular programming

(1): module writing

Original Writing
// A module is a set of methods to implement specific functions. If you simply put different functions (and the variables that record the status) together, it is a module;
Function m1 (){
//...
}
Function m2 (){
//...
}
// The above functions m1 () and m2 () form a module, which can be called directly during use;
// Disadvantage: "contaminated" global variables; there is no guarantee that there will be no conflict with other modules of the variable name, and no direct relationship can be seen between module members;

2. Object writing

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// Write a module as an object. All module members are put into this object;

Var module = new Object ({

_ Count: 0,

M1: function (){

//...

},

M2: function (){

//...

}

});

// The above functions m1 () and m2 () are encapsulated in the module object; the attributes of this object are directly called during use;

Module. m1 ();

// However, this write method exposes all module members and the internal status can be changed externally;

Module. _ count = 4;

3. Execute function writing immediately

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Var module = (function (){

Var _ count = 0;

Var m1 = function (){

//...

};

Var m2 = function (){

 

};

Return {

M1: m1,

M2: m2

};

})();

// Using the above Code, external code cannot read the internal _ count variable;

Lele.info (module. _ count); // undefined;

// The above method is the basic method of writing JavaScript modules;

Quad-zoom Mode

1

2

3

4

5

6

7

8

// If the module is large, it must be divided into several parts, or a module must inherit from another module, then it is necessary to adopt the "zoom mode ";

Var module = (function (mod ){

Mod. m3 = function (){

//...

};

Return mod;

}) (Module );

// The code above adds a new method m3 () to the module, and then returns the new module;

5-width zoom-in Mode

1

2

3

4

5

6

7

// In the browser environment, each part of the module is usually obtained from the Internet, and sometimes cannot know which part will be loaded first;

// If you use the method described in the previous section, the first part of the execution may load a non-null object. In this case, you must use the "wide amplification mode ";

Var module = (function (mod ){

//...

Return mod;

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

// In contrast to the zoom-in mode, the parameter "wide zoom-in mode" means "immediate function execution" can be a null object;

Six input global variables

1

2

3

4

5

6

7

// Independence is an important feature of the module. It is best not to directly interact with other parts of the program within the module;

// To call global variables within the module, other variables must be explicitly input to the module;

Var module = (function ($, YAHOO ){

//...

}) (JQuery, YAHOO );

// The module above needs to use the jQuery library and YUI library, and the two libraries (actually two modules) are used as the parameter input module;

// In addition to ensuring the independence of modules, the dependency between modules becomes obvious;

Chapter 2 JavaScript Modular programming (II): AMD specifications

Specification of Module 1
// Currently, there are two common JavaScript module specifications: CommonJS and AMD;

2. CommonJS
// Node. js uses the javascript language for server-side programming, which marks the birth of "JavaScript Modular programming;
// The node. js module system is implemented by referring to the CommonJS specification;
In CommonJS, there is a global method require () for Loading modules;
Var math = require ('Math'); // load the module;
Math. add (2, 3); // call the module method => 5;

3. browser Environment
// The code in the previous section has a big problem in the browser;
Var math = require ('Math ');
Math. add (2, 3 );
// Problem: math. add (2, 3) is executed only after loading of math. js such as require ('Math );
// The browser module cannot adopt "synchronous loading", but can only adopt "asynchronous loading"; ==> AMD;

Four AMD
AMD (Asynchronous Module Definition) Asynchronous Module Definition;
// The asynchronous loading module is used. The module loading does not affect the execution of subsequent statements. All statements dependent on this module are defined in a callback function,
// This callback function will run only after loading is complete;
// AMD also uses the require () statement to load the module, but it requires two parameters:
Require ([module], callback );
// Module: it is an array and its members are the modules to be loaded;
// Callback: the callback function after successful loading;
Require (['Math'], function (math ){
Math. add (2, 3 );
});
// The math. add () and math modules are not synchronized, And the browser will not be suspended; therefore, AMD is suitable for the browser environment;

Chapter 3 JavaScript Modular programming (III): Use of require. js
1. Why do I use require. js?
// Multiple js files need to be loaded in sequence;
// Disadvantage:
// 1. When loading, the browser will stop rendering the webpage. The more files are loaded, the longer the webpage will lose response;
// 2. Due to the dependency between js files, the loading sequence must be strictly ensured. When the dependency is complex, coding and maintenance become difficult;
// Therefore, require. js solves these two problems:
// 1. asynchronous loading of js files to prevent webpage response loss;
// 2. Manage dependencies between modules to facilitate code compilation and maintenance;

2. Loading of require. js
1. Load require. js
<Script scr = "js/require. js" defer async = "true"> </script>
// The async attribute indicates that the file needs to be asynchronously loaded to avoid webpage response loss. IE does not support this attribute and only supports defer. Therefore, defer is also written;
2. Load main. js
<Script src = "js/require. js" data-main = "js/main"> </script>
// The function of the data-main attribute is to specify the main module of the webpage program => main. js. This file will be first loaded by require. js;
// Because the default file Suffix of require. js is js, You Can abbreviated main. js as main;

Writing of main. js in the three main modules
1. If main. js does not rely on any other modules, JavaScript code can be directly written;
// Main. js
Alert ('Load successful! ');
2. If main. js depends on the module, use the require () function defined in AMD specifications;
// Main. js
Require (['lelea', 'leleb', 'lelec'], function (moduleA, moduleB, moduleC ){
//...
})
// The require () function receives two parameters:
// Parameter 1: array, indicating the dependent modules, that is, the three dependent modules of the main module;
// Parameter 2: callback function. After all the modules specified on the current plane are loaded successfully, the callback function is called. The loaded modules are passed in as parameters, these modules can be used inside the callback function;
// Require () asynchronously loads the module and the browser does not lose the response. The callback function specified by require () runs only after the previous modules are loaded successfully, solving the dependency problem;
Instance:
Require (['jquery ', 'underscore', 'backone'], function ($, _, backbone ){
//...
});

Four-module Loading
// Use the require. config () method to customize the module loading behavior;
// Require. config () is written in the header of the main module (main. js;
// The parameter is an object. The paths attribute of this object specifies the loading path of each module;
// Set the file default for the following three modules and a directory for main. js;
Require. config ({
Paths :{
"Jquery": "jquery. min ",
"Underscore": "underscore. min ",
"Backbone": "backbone. min"
}
});

// If the loaded module and the main module are not in the same directory, specify the path one by one;
Require. config ({
Paths :{
"Jquery": "lib/jquery. min ",
"Underscore": "lib/underscore. min ",
"Backbone": "lib/backbone. min"
}
});
// Or directly change the base Directory (baseUrl)
Require. config ({
BaseUrl: "js/lib ",
Paths :{
"Jquery": "jquery. min ",
"Underscore": "underscore. min ",
"Backbone": "backbone. min"
}
});

// If the module is on another host, you can specify its URL directly.
Require. config ({
Paths :{
"Jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"
}
});
// Require. js requires that each module be a separate js file. In this way, if multiple modules are loaded, multiple HTTP requests will be sent, affecting the loading speed of webpages;
// Therefore, require. js provides an optimization tool. After the module is deployed, you can use this tool to merge multiple modules into one file to reduce the number of HTTP requests;

Writing of AMD Module

// The modules loaded by require. js adopt AMD specifications. That is to say, the modules must be written in accordance with AMD regulations;
// Specifically, the module must be defined using a specific define () function; if a module does not depend on other modules, it can be directly defined in the define () function;
// Define the math module in math. js
// Math. js
Define (function (){
Var add = function (x, y ){
Return x + y;
};
Return {
Add: add
};
});
// Load the math module in main. js
Require (['Math'], function (math ){
Alert (math. add (1, 1 ));
});
// If this module depends on other modules, the first parameter of the define () function must be an array to indicate the dependency of this module;
// Math. js
Define (['mylib '], function (myLib ){
Function foo (){
MyLib. doSomething ();
}
Return {
Foo: foo
};
});
// When the require () function loads the above module, the myLib. js file will be loaded first;

6. Load nonstandard modules

// Load nonstandard modules. Before loading with require (), use the require. config () method to define some of their features;
Require. config ({
Shim :{
'Underscore ':{
Exports :'_'
},
'Background ':{
Deps: ['underscore ', 'jquery'],
Exports: 'backone'
}
}
});
// Require. config () receives a configuration object. In addition to the paths attribute mentioned earlier, this object also has a shim attribute, which is used to configure incompatible modules;
// (1). Define the deps array to indicate the dependency of the module;
// (2). Define the exports value (name of the output variable) to indicate the name of the module during external calls;
For example, jQuery plug-in
Shim :{
'Jquery. scroll ':{
Deps: ['jquery '],
Exports: 'jquery. fn. scroll'
}
};

Seven require. js plug-ins

1. domready: enables the callback function to run after the DOM structure of the page is loaded;
Require (['domainready! '], Function (doc ){
// Called once the DOM is ready;
})
2. text and image: Allow require. js to load text and image files;
Define (['text! Review.txt ', 'image! Cat.jpg '], function (review, cat ){
Console. log (review );
Document. body. appendChild (cat );
});

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.