Home Web Front-end JS Tutorial Detailed explanation of JavaScript modular programming

Detailed explanation of JavaScript modular programming

Mar 12, 2017 pm 01:21 PM
javascript

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


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模块的基本写法;
Copy after login


Four-wide zoom mode


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


Five-wide zoom mode


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


Six input global variables


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


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

// 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

// 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles