国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1 What is modular programming
2 Why modularize
3 AMD
4 CommonJS
5 總結(jié)
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()

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>

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)

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

// ? 代表該參數(shù)可選
    define(id?, dependencies?, factory);
  • 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();
       }
   });

An anonymous module that returns objects:

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

A module with no dependencies can directly define objects:

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

How to use

AMD uses the require statement to load the module

require([module],callback);
  • 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)
})

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)
})// 使用// 

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"
    }
})

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",

    }

  });

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;);

Then, just You can call the methods provided by util

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

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)
    }
}

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;

5 總結(jié)

CommonJS 則采用了服務(wù)器優(yōu)先的策略,使用同步方式加載模塊,而 AMD 采用異步加載的方式。所以如果需要使用異步加載 js 的話建議使用 AMD,而當(dāng)項(xiàng)目使用了 npm 的情況下建議使用 CommonJS。

相關(guān)推薦:

論JavaScript模塊化編程

requireJS框架模塊化編程實(shí)例詳解

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

See all articles