Implementing a modular organization under JavaScript

Source: Internet
Author: User

Previous words

Java has class files, Python has import keywords, Ruby has require keywords, C # has a using keyword, PHP has include and require, CSS has @import keywords, but for ES5 version of JavaScript , JavaScript introduces code through script tags in a haphazard way, language itself is unstructured and constrained, and people have to use the command space to artificially constrain code in order to achieve security and ease of use. This article describes in detail the module organization in JavaScript

Anti-pattern

Anti-pattern (anti-pattern) means that no module system is used

Simply put the different functions (and the variables that record the state) together, even if it is a module

  function M1 () {  //...  }  function  m2 () {  //... }

The above functions M1 () and M2 () to form a module. When used, call directly on the line.

The disadvantage of this approach is obvious: "Pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship between

Literal quantity

In order to solve the above shortcomings, the module can be written as a literal, all the module members are placed in this object

  var New  0function  () {  //...  function  () {  //... }});

The above functions M1 () and M2 () are encapsulated in the Module1 object. When used, it is called the property of the object

MODULE1.M1 ();

However, this notation exposes all module members, and the internal state can be overridden externally. For example, external code can directly change the value of an internal counter

Module1._count = 5;

Iife

Use the "Execute functions Now" (immediately-invoked function Expression,iife) to achieve the purpose of not exposing private members

  var module1 = (function() {  var _count = 0;  varfunction() {  //...    };  varfunction() {  //...    };   return  {m1:m1, m2:m2}; })();

Using the notation above, external code cannot read the internal _count variable

// undefined

Iife Pass

If one module needs to inherit another module, the Iife must be passed

  var function  function  () {  //...    };  return| | {});

Name space

If the Iife method is used, the global environment is still polluted as the module increases.

The namespace (Namespace) can address the global environment's pollution problem by exposing only global variables similar to a ' Namespace ' to implement all the module declarations.

//Math.jsNamespace (' math ', [],function(){  functionAdd (A, b) {returnA +b;} functionSub (A, b) {returnAb;} return{add:add, sub:sub}})//Calculator.jsNamespace (' Calculator ', [' Math '],function(m) {varAction = ' Add '; functionCompute (A, b) {returnM[action] (A, b); }  return{Compute:compute}})
varNamespace = (function(){    //Cache All Modules    varCache = {}; functionCreatemodule (name/*Module Name*/, Deps/*Dependency List*/, definition/*definition*/){        //if only the module name, the direct output        if(Arguments.length = = 1){            returnCache[name]; }        //get the dependencies of all modulesDeps = Deps.map (function(depname) {returnNS (Depname); })        //initializes the module and returnsCache[name] = definition.apply (NULL, Deps); returnCache[name]; }    returncreatemodule;})

At last

Although, using namespaces can solve the problem of global environmental pollution, but it can't solve the problem of module dependency management.

As shown, Module2 relies on Module1 and Module3, the code is as follows

<script src= "Module1.js" ></script><script src= "module3.js" ></script><script src= " Module2.js "></script>

However, if the module is organized as follows

Even, as shown below

In this case, manual processing of dependencies between modules is unrealistic and requires the use of AMD, CMD, ES6 module, etc. to handle

Implementing a modular organization under JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.