Table of Contents
1 What is modular programming
2 Why modularize
3 AMD
4 CommonJS
5 总结
Home Web Front-end JS Tutorial What is modular programming? Summary of js modular programming

What is modular programming? Summary of js modular programming

Aug 10, 2018 pm 04:51 PM

1 What is modular programming

2 Why should we modularize

3 AMD

4 CommonJS

5 Summary

To understand a technology, you must first understand the background of the technology and the problems it solves, rather than simply knowing how to use it. The previous state may have been to understand just for the sake of understanding, without knowing the actual causes and benefits, so let’s summarize it today.

1 What is modular programming

Let’s look at Baidu Encyclopedia’s definition

Modular programming refers to dividing a large program according to its functions during programming It is divided into several small program modules, each small program module completes a certain function, and the necessary connections are established between these modules, and the entire function is completed through the mutual cooperation of the modules.

For example, java's import, C#'s using. My understanding is that through modular programming, different functions can be separated, and modification of one function will not affect other functions.

2 Why modularize

Let’s look at the following example

// A.jsfunction sayWord(type){
    if(type === 1){
        console.log("hello");
    }else if(type === 2){
        console.log("world");
    }
}// B.jsfunction Hello(){
    sayWord(1);
}// C.jsHello()
Copy after login

Assume that among the above three files, B.js references the content in A.js, and C.js The content in B.js is also quoted. If the person writing C.js only knows that B.js is quoted, then he will not quote A.js, which will cause a program error, and the reference order of the files cannot be wrong. It brings inconvenience to the debugging and modification of the overall code.

There is another problem. The above code exposes two global variables, which can easily cause pollution of global variables

3 AMD

AMD is Asynchronous Module Definition (asynchronous module definition) . The module is loaded asynchronously. The loading of the module will not affect the execution of subsequent statements.

Assume the following situation

// util.jsdefine(function(){
    return {
        getFormatDate:function(date,type){
            if(type === 1){                return '2018-08-9'
            }            if(type === 2){                return '2018 年 8 月 9 日'
            }
        }
    }
})// a-util.jsdefine(['./util.js'],function(util){
    return {
        aGetFormatDate:function(date){
            return util.getFormatDate(date,2)
        }
    }
})// a.jsdefine(['./a-util.js'],function(aUtil){
    return {
        printDate:function(date){
            console.log(aUtil.aGetFormatDate(date))
        }
    }
})// main.jsrequire(['./a.js'],function(a){
    var date = new Date()
    a.printDate(date)
})
console.log(1);// 使用// <script src = "/require.min.js" data-main="./main.js"></script>
Copy after login

The page will print 1 first, and then August 9, 2018 will be printed. Therefore, the loading of AMD will not affect subsequent statement execution.

What will happen if it is not loaded asynchronously

var a = require(&#39;a&#39;);
console.log(1)
Copy after login

The following statements need to wait for a to be loaded before they can be executed. If the loading time is too long, the entire program will be stuck here. Therefore, the browser cannot load resources synchronously, which is also the background of AMD.

AMD is a specification for modular development on the browser side. Since this specification is not originally supported by JavaScript, third-party library functions, namely RequireJS, need to be introduced when developing using the AMD specification.

RequireJS main problems solved

  • Enable JS to be loaded asynchronously to avoid page loss of response

  • Manage dependencies between codes sex, which is conducive to code writing and maintenance

Let’s take a look at how to use require.js

If you want to use require.js, you must first define

// ? 代表该参数可选
    define(id?, dependencies?, factory);
Copy after login
  • id: refers to the name of the defined module

  • dependencies: is an array of modules that the defined module depends on

  • factory: Initialize the function or object to be executed for the module. If it is a function, it should be executed only once. If it is an object, this object should be the output value of the module.

    For specific specifications, please refer to AMD (Chinese version)
    For example, create a module named "alpha", use require, exports, and a module named "beta":

define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {
       exports.verb = function() {
           return beta.verb();           //Or:
           return require("beta").verb();
       }
   });
Copy after login

An anonymous module that returns objects:

define(["alpha"], function (alpha) {
       return {
         verb: function(){
           return alpha.verb() + 2;
         }
       };
   });
Copy after login

A module with no dependencies can directly define objects:

define({
     add: function(x, y){
       return x + y;
     }
   });
Copy after login

How to use

AMD uses the require statement to load the module

require([module],callback);
Copy after login
  • module: is an array, the members inside are the modules to be loaded

  • callback: load Callback function after success

For example

require([&#39;./a.js&#39;],function(a){
    var date = new Date()
    a.printDate(date)
})
Copy after login

The specific usage method is as follows

// util.jsdefine(function(){
    return {
        getFormatDate:function(date,type){
            if(type === 1){                return '2018-08-09'
            }            if(type === 2){                return '2018 年 8 月 9 日'
            }
        }
    }
})// a-util.jsdefine(['./util.js'],function(util){
    return {
        aGetFormatDate:function(date){
            return util.getFormatDate(date,2)
        }
    }
})// a.jsdefine(['./a-util.js'],function(aUtil){
    return {
        printDate:function(date){
            console.log(aUtil.aGetFormatDate(date))
        }
    }
})// main.jsrequire([&#39;./a.js&#39;],function(a){
    var date = new Date()
    a.printDate(date)
})// 使用// 
Copy after login

Assume there are 4 files here, util.js, a- util.js refers to util.js, a.js refers to a-util.js, and main.js refers to a.js.

Among them, the data-main attribute is used to load the main module of the web page program.

The above example demonstrates the simplest way to write a main module. By default, require.js assumes that dependencies are in the same directory as the main module.

Use the require.config() method to customize the loading behavior of the module. require.config() It is written at the head of the main module (main.js). The parameter is an object. The paths attribute of this object specifies the loading path of each module.

require.config({
    paths:{        "a":"src/a.js",        "b":"src/b.js"
    }
})
Copy after login

There is also a The first method is to change the base directory (baseUrl)

require.config({

    baseUrl: "src",

    paths: {

      "a": "a.js",
      "b": "b.js",

    }

  });
Copy after login

4 CommonJS

commonJS is the modular specification of nodejs. It is now widely used in the front end. Due to the high degree of automation of the build tool, the use of npm The cost is very low. commonJS does not load JS asynchronously, but loads it synchronously in one go.

In commonJS, there is a global method require(), which is used to load modules, such as

const util = require(&#39;util&#39;);
Copy after login

Then, just You can call the methods provided by util

const util = require(&#39;util&#39;);var date = new date();
util.getFormatDate(date,1);
Copy after login

commonJS There are three types of module definitions, module definition (exports), module reference (require) and module label (module)

exports() object Used to export variables or methods of the current module, the only export port. require() is used to introduce external modules. The module object represents the module itself.

Give me a chestnut

// util.jsmodule.exports = {
    getFormatDate:function(date, type){
         if(type === 1){                return &#39;2017-06-15&#39;
          }          if(type === 2){                return &#39;2017 年 6 月 15 日&#39;
          }
    }
}// a-util.jsconst util = require(&#39;util.js&#39;)
module.exports = {
    aGetFormatDate:function(date){
        return util.getFormatDate(date,2)
    }
}
Copy after login

Or the following method

 // foobar.js
 // 定义行为
 function foobar(){
         this.foo = function(){
                 console.log(&#39;Hello foo&#39;);
        }  
         this.bar = function(){
                 console.log(&#39;Hello bar&#39;);
          }
 } // 把 foobar 暴露给其它模块
 exports.foobar = foobar;// main.js//使用文件与模块文件在同一目录var foobar = require(&#39;./foobar&#39;).foobar,
test = new foobar();
test.bar(); // &#39;Hello bar&#39;
Copy after login

5 总结

CommonJS 则采用了服务器优先的策略,使用同步方式加载模块,而 AMD 采用异步加载的方式。所以如果需要使用异步加载 js 的话建议使用 AMD,而当项目使用了 npm 的情况下建议使用 CommonJS。

相关推荐:

论JavaScript模块化编程

requireJS框架模块化编程实例详解

The above is the detailed content of What is modular programming? Summary of js 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles