Home > Web Front-end > JS Tutorial > body text

How to understand JavaScript modularity?

coldplay.xixi
Release: 2020-06-30 15:00:51
Original
2688 people have browsed it

The understanding of JavaScript modularity is: 1. Module mode, which opens a new scope through the characteristics of closure, which alleviates the problems of global scope naming conflicts and security; 2. CommonJS mode, Mainly used in Node development, each file is a module, and each file has its own scope.

How to understand JavaScript modularity?

The understanding of JavaScript modularity is:

1. Module mode

Before the formation of modular specifications, JS developers used the Module design pattern to solve the pollution problem of JS global scope. The Module pattern was originally defined as a method of providing private and public encapsulation for classes in traditional software engineering. In JavaScript, Module mode uses anonymous function self-calling (closure) to encapsulate, and distinguishes private members and public members through customized exposure behavior.

let myModule = (function (window) {
    let moduleName = 'module'  // private
    // public
    function setModuleName(name) {
      moduleName = name
    }
    // public
    function getModuleName() {
      return moduleName
    }
    return { setModuleName, getModuleName }  // 暴露行为
  })(window)
Copy after login

The above example is a way of writing the Module pattern. It opens a new scope through the closure feature, which alleviates the problems of global scope naming conflicts and security. However, developers could not use it to organize and split code, so the modular specification based on this emerged.

Related learning recommendations: javascript video tutorial

2. CommonJS

CommonJS is mainly used in In Node development, each file is a module, and each file has its own scope. Expose public members through module.exports. For example:

// 文件名:x.js
let x = 1;
function add() {
  x += 1;
  return x;
}
module.exports.x = x;
module.exports.add = add;
Copy after login

In addition, CommonJS introduces module dependencies through require(). The require function can introduce Node’s built-in modules, custom modules and third-party modules such as npm. .

// 文件名:main.js
let xm = require('./x.js');
console.log(xm.x);  // 1
console.log(xm.add());  // 2
console.log(xm.x);   // 1
Copy after login

We can see from the above code that the require function loads x.js synchronously and returns the copy value of the module.exports output literal.

Some people may askmodule.exports.x = x;Isn’t it an assignment? How can it be a big deal? We say that the Module pattern is the cornerstone of the modular specification, and CommonJS is also an encapsulation of the Module pattern. We can completely use the Module mode to achieve the above code effect:

let xModule = (function (){
  let x = 1;
  function add() {
    x += 1;
    return x;
  }
  return { x, add };
})();
let xm = xModule;
console.log(xm.x);  // 1
console.log(xm.add());  // 2
console.log(xm.x);   // 1
Copy after login

Through the CommonJS principle simulated by the Module mode, we can well explain the characteristics of CommonJS. Because CommonJS needs to obtain the return value of the anonymous function self-call through value assignment, the require function is synchronous when loading the module. However, the loading mechanism of CommonJS modules limits the use of CommonJS on the client, because synchronously loading CommonJS modules through HTTP is very time-consuming.

3, AMD

// 定义AMD规范的模块
define([function() {
  return 模块
})
Copy after login

Different from CommonJS, AMD The standard dependent modules are loaded asynchronously, while the defined modules are loaded as It is executed as a callback function and relies on the require.js module management tool library. Of course, the AMD specification is not encapsulated by anonymous function self-calling. We can still use the principle of closure to implement the private members and public members of the module:

define(['module1', 'module2'], function(m1, m2) {
  let x = 1;
  function add() {
    x += 1;
    return x;
  }
  return { add };
})
Copy after login

4 , CMD

CMD is the standardized output of module definition during the promotion process of SeaJS. AMD recommends dependencies in front, CMD recommends dependencies nearby.

define(function(require, exports, module) {
  //  同步加载模块
  var a = require('./a');
  a.doSomething();
  // 异步加载一个模块,在加载完成时,执行回调
  require.async(['./b'], function(b) {
    b.doSomething();
  });
  // 对外暴露成员
  exports.doSomething = function() {};
});
// 使用模块
seajs.use('path');
Copy after login

CMD integrates the features of CommonJS and AMD and supports synchronous and asynchronous loading of modules. CMD does not execute a dependent module after loading it, it just downloads it. After all dependent modules are loaded, it enters the main logic. The corresponding module is executed only when the require statement is encountered. In this way, the execution order of the modules is completely consistent with the writing order. of. Therefore, there is no HTTP request process when the require function in CMD loads the module synchronously.

5. ES6 module

The modularization of ES6 is no longer a standard, but a feature of the JS language. With the launch of ES6, AMD and CMD have become history. Compared with the modular specification, the ES6 module has two major characteristics:

  • The modular specification outputs a copy of the value, while the ES6 module outputs a reference to the value.

  • The modular specification is loaded at runtime, and the ES6 module is a compile-time output interface.

The output of the modular specification is an object, which will only be generated after the script is run. The ES6 module is not an object. The ES6 module is a multi-object output and multi-object loading model. In principle, the modular specification is an encapsulation of anonymous function self-calling, while the ES6 module uses anonymous function self-calling to call output members.

The above is the detailed content of How to understand JavaScript modularity?. 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