Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript modular programming

Detailed explanation of JavaScript modular programming

高洛峰
高洛峰Original
2017-03-12 13:21:271371browse

This article explains JavaScript modular programming in detail

Chapter 1 JavaScript modular programming

(1): How to write modules

-Original writing method
/ / A module is a set of methods to implement a specific function; as long as different functions (and variables that record status) are simply put together, it is considered a module;
function m1(){
                                                                                                                                                                                                                    m1(){ ), form a module; just call it directly when using;
// Disadvantages: "pollution" of global variables; there is no guarantee that variable names will not conflict with other modules, and there is no direct relationship between module members;


Object
How to write

// 把模块写成一个对象,所有的模块成员都放到这个对象里面;
  var module = new Object({
    _count:0,
    m1:function(){
      // ...
    },
    m2:function(){
      // ...
    }
  });
// 上面的函数m1()和m2(),都封装在module对象里;使用时直接调用这个对象的属性;
  module.m1();
// 但是,这样的写法会暴露所有模块成员,内部状态可以被外部改写;
  module._count = 4;


Three how to write the immediate execution function


  var module = (function(){
    var _count = 0;
    var m1 = function(){
      // ...
    };
    var m2 = function(){

    };
    return {
      m1:m1,
      m2:m2
    };
  })();
// 使用上面的写法,外部代码无法读取内部的_count变量;
  console.info(module._count); // undefined;
// 上面的写法就是JavaScript模块的基本写法;


Four-wide zoom mode


// 如果模块很大,必须分成几个部分,或者一个模块需要继承另一个模块,这时就有必要采用"放大模式";
  var module = (function(mod){
    mod.m3 = function(){
      // ...
    };
    return mod;
  })(module);
// 上面的代码为module模块添加了一个新方法m3(),然后返回新的module模块;


Five-wide zoom mode


// 在浏览器环境中,模块的各个部分通常都是从网上获取的,有时无法知道哪个部分会先加载;
// 如果采用上一节的写法,第一个执行的部分有可能加载一个不存在的空对象,这时就要采用"宽放大模式";
  var module = (function(mod){
    // ...
    return mod;
  })(window.module || {});
// 与"放大模式"相比,"宽放大模式"就是"立即执行函数"的参数可以是空对象;


Six input global variables


// 独立性是模块的重要特点,模块内部最好不与程序的其他部分直接交互;
// 为了在模块内部调用全局变量,必须显式地将其他变量输入模块;
  var module = (function($,YAHOO){
    // ...
  })(jQuery,YAHOO);
// 上面的module模块需要使用jQuery库和YUI库,就把这两个库(其实是两个模块)当作参数输入module;
// 这样做除了保证模块的独立性,还使得模块之间的依赖关系变得明显;


Chapter 2 JavaScript Modular Programming (2): AMD Specification

One Module Specification
// Currently, there are two popular JavaScript module specifications: CommonJS and AMD;

二CommonJS

//

node.js
Using javascript language for server-side programming marks the official birth of "JavaScript modular programming";

// node.js module system , which is implemented with reference to the CommonJS specification;

In CommonJS, there is a global method
require(), which is used to load modules; var math = require('math'); // Load module;
math.add(2,3); //Call module method=>5;
Three browser environment//The code in the previous section runs in the browser There will be a big problem;
var math = require('math');
math.add(2,3);

// Problem: You must wait for math in require('math'). Math.add(2,3) will be executed only after js loading is completed;

// Therefore, the browser module cannot use "synchronous loading" and can only use "asynchronous loading";==>AMD;

四AMD
AMD (Asyn
chr
onous Module Definition) asynchronous module definition;

// Asynchronous loading of modules is used. The loading of the module does not affect the running of the statements behind it. All dependencies The statements of this module are all defined in a

callback function
, // This callback function will not run until the loading is completed; // AMD also uses the require() statement to load the module , but it requires two parameters:
require([module],callback);// module: is an array
, the members inside are the modules to be loaded;
/ / callback: is the callback function after successful loading;
require(['math'],function(math){
math.add(2,3); });// Math.add() and math module loading are not synchronized, and the browser will not freeze; therefore, AMD is more suitable for the browser environment;

Chapter 3 JavaScript Modular Programming (3): require.js Usage
1 Why use require.js
// Multiple js files need to be loaded in sequence;
// Disadvantages:

// 1. When loading, the browser will stop rendering the web page and load the file The more, the longer the webpage will lose response;

// 2. Since there are dependencies between js files, the loading order must be strictly guaranteed. When the dependencies are complex, the writing and maintenance of the code will becomes difficult;
// So require.js solves these two problems:
// 1. Implement asynchronous loading of js files to avoid web pages losing response;
// 2. Management between modules Dependencies facilitate code writing and maintenance;

Loading of require.js
1. Loading require.js
98cb06b20f8457ecce5d74f566f6aa182cacc6d41bbb37262a98f745aa00fbf0
// The async attribute indicates that this file needs to be loaded asynchronously to prevent the web page from losing response; IE does not support this attribute and only supports defer, so write defer as well;

2 .Load

main
.js
35be17e58c59207c30045b58673f385a2cacc6d41bbb37262a98f745aa00fbf0
// data-main The function of the attribute is to specify the main module of the web program => main.js. This file will be loaded by require.js first;
// Since the default file suffix of require.js is js, you can main.js is abbreviated as main;

How to write the three main modules main.js
1. If main.js does not depend on any other modules, you can directly write JavaScript code;
// main.js
alert('Loading successful! ');
2. If main.js depends on the module, then you need to use the require() function defined by the AMD specification;
// main.js
require(['moduleA','moduleB ','moduleC'],function(moduleA,moduleB,moduleC){
// ...
})
// The require() function receives two parameters:
// Parameters One: Array, indicating the dependent modules, that is, the three modules that the main module depends on;
// Parameter two: Callback function, it will be called when all the previously specified modules are loaded successfully; the loaded module will Pass this function in as a parameter, so that these modules can be used inside the callback function;
// require() loads modules asynchronously, and the browser will not lose response; for the callback function it specifies, only the previous modules are loaded successfully It will run only after , which solves the dependency problem;
Example:
require(['jquery','underscore','backbone'],function($,_,Backbone){
/ / ...
});

Loading of four modules
//Use the require.config() method to customize the loading behavior of the module;
// require. config() is written at the head of the main module (main.js);
// The parameter is an object, and the paths attribute of this object specifies the loading path of each module;
// Set the following three modules The file is in the same directory as main.js by default; ",
"backbone":"backbone.min"
}
});

// If the loaded module and the main module are not in the same directory, you must 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 also specify its URL directly
require.config({
      paths:{

              "jquery":" https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"

}
});
// require.js requirement, each module is a separate js file; in this case, if multiple modules are loaded, multiple HTTP requests will be issued, which will affect the loading speed of the web page;
// 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;

How to write the five AMD modules

// Modules loaded by require.js adopt AMD specifications, that is to say, modules must be written in accordance with AMD regulations;
// Specifically, modules must be defined using a specific define() function ;If a module does not depend on other modules, it can be defined directly 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 also depends on other modules, then the first parameter of the define() function must be an array to indicate the dependencies of the module;
// math.js
define(['myLib '],function(myLib){
function foo(){
myLib.doSomething();
;
// When the require() function loads the above module, the myLib.js file will be loaded first;

6 Loading non-standard modules

// Loading non-standard modules Before loading modules with require(), you must first use the require.config() method to define some of their characteristics; ##                                                                                        #            }
}
});

// require.config() receives a configuration object. In addition to the paths attribute mentioned earlier, this object also has a shim attribute, which is specially used to configure incompatible modules;

// (1). Define the deps array to indicate the dependency of the module;

// (2). Define the exports value (output variable name) to indicate the name of this module when called externally;

For example: jQuery plug-in
shim:{
                                                                                                                                                                                            use using using shim using                 use using shim through out ’s shim out’s ’ through ’ s ‐    ‐ ‐ dps: ['jquery']                        ## };

Seven require.js plugin

1.domready: allows the callback function to run after the page DOM structure is loaded;
require(['domready!'], 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);
});

The above is the detailed content of Detailed explanation of JavaScript modular programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn