Home > Web Front-end > JS Tutorial > What is modular programming? Summary of js modular programming

What is modular programming? Summary of js modular programming

php是最好的语言
Release: 2018-08-10 16:51:55
Original
6020 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template