Implementing a modular organization under JavaScript

Source: Internet
Author: User

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

var module1 = new Object ({_count:0, m1:function () {//...}, M2:function () {//...} });

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

Console.info (Module1._count); Undefined

Iife Pass

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

var Module1 = (function (mod) {mod.m3 = function () {//...};  return mod; }) (Window.module1 | | {});

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>


650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

var namespace =  (function () {    //cache all modules     var  Cache = {};    function createmodule (name/* module name */,deps/* dependency list */,definition/* Definition */) {        //Direct output if only module name is available          if (arguments.length === 1) {             return cache[name];        }         //gets the dependency         deps = deps.map of all modules ( function (Depname) {            return  namespace (depname);          })          //Initialize module and return to         cache[name] =  Definition.apply (null,deps);         return cache[name];    }     Return createmodule;}) ()

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/740839/201705/740839-20170512163838676-1698856628. PNG "style=" border:none;margin-top:20px;margin-bottom:20px; "/>

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

However, if the module is organized as follows

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/740839/201705/740839-20170512164300832-421694311. PNG "style=" border:none;margin-top:20px;margin-bottom:20px; "/>

Even, as shown below

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/740839/201705/740839-20170512164314582-1695611926. PNG "style=" border:none;margin-top:20px;margin-bottom:20px; "/>

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.