Understanding JavaScript Modular _javascript Techniques

Source: Internet
Author: User

Modularity is a common programming best practice. The modularization of the program makes it easier for us to use other people's code, what functions we want, what modules to load, so as to improve the efficiency of code utilization and increase the speed of development.

Module is like a building block, with it, we can build a variety of functional styles of the program. What are the characteristics of building blocks? Small and simple. In the same way, the modules in our program have to do this to make sure that the function you create is just one job at a time so that other developers can simply debug and modify your code without having to browse through all the code to figure out what each piece of code does. Only by doing something as small and simple as this can you achieve its universal function.

A modular approach to JavaScript
1. Function encapsulation
The scope of JavaScript is based on functions, so we can use functions as modules.

function fn1 () {
  //code
}

function fn2 () {
  //code
}

Disadvantage: "Pollution" of the global variable, can not guarantee that no variable name conflicts with other modules

2. Object

var myModule1 = {
  fn1:function () {
    //code
  },
  fn2:function () {
    //code
  }
}

Disadvantage: All module members will be exposed, internal state can be externally rewritten

Immediate self-execution function--recommended

var MyModule = (function () {
  function fn1 () {
    //code
  },
  function fn2 () {
    //code
  },
  return {
    fn1:fn1,
    fn2:fn2
  };
}) ();

Second, small and simple
As for small and simple, let's look at an example where we now want to write a function that creates a new link and adds a class for the type "mailto" hyperlink. You can do this:

function addlink (text, URL, parentelement) {
  var NewLink = document.createelement (' a ');//Create a
  label Newlink.setattribute (' href ', url);//Set HREF attribute
  newlink.appendchild (document.createTextNode (text) for a label); Add text to a tag
  if (Url.indexof ("mailto:") ==-1) {
    newlink.classname = ' mail ';
  }
  Parentelement.appendchild (NewLink);//Add a label to page
}

This can work, but you may find yourself not able to add other functions, so this function does not apply. Therefore, the more special the function, the more difficult it is to apply to different situations.
The functional notation here does not meet the requirements of modularity--a function that only does one thing. We'll adapt the function by:

function Createlink (text,url) {
  var NewLink = document.createelement (' a ');
  Newlink.setattribute (' href ', url);
  Newlink.appendchild (document.createTextNode (text));
  return newlink;
}

Here the Createlink function only does one thing--Create and return a label (small and simple) to add to the page so that we can call such a function whenever we need to create a hyperlink.

Third, Commonjs
In the browser environment, no module is not particularly big problem, after all, the complexity of the Web page program is limited, but on the server side, must have a module with the operating system and other applications to interact, otherwise it is impossible to program. Although JavaScript has been on the web for so many years, the first popular modular specification is brought by server-side JavaScript applications, and the COMMONJS specification is carried forward by Nodejs, marking the formal stage of JavaScript modular programming.
Node.js module system, is based on the COMMONJS specification. In Commonjs, there is a global method require (), which is used to load modules.
Load module:

var math = require (' math ');
Call Module:

Math.add (2,3)
The COMMONJS specification does not apply to the browser environment because it has a significant limitation, the second line in the example above Math.add (2, 3) Must be completed after the math.js load to run, and the module is placed on the server side, so it may have to wait a long time, the waiting time depends on the speed of the network.

The COMMONJS specification is applicable to the server side because all modules are stored on the local hard drive for the service side, and can be completed synchronously, while the wait time is the read time of the hard disk

Four, how should the module define and how to load?
AMD
Asynchronous module definition asynchronous modules, main representative: Require.js
Objective:
(1) To realize the asynchronous loading of JS files to avoid web page loss of response;
(2) Management of the dependencies between modules, easy to write code and maintenance.

1. Definition Module

Define (["./cart", "./inventory"], function (cart, inventory) {
  //via [] introduces dependency return
  {
    color: "Blue",
    Size: "Large",
    addtocart:function () {
      inventory.decrement (this);
      Cart.add (this);}}
);

2. Loading module

Require (["Some/module", "My/module", "A.js", "B.js"],
function (Somemodule,  mymodule) {
  //this function would be called the dependencies
  //listed above are loaded. This this function could
  //be called before the page is loaded.
  This callback is optional.
}
 );

Cmd
Common module definition Common modules, the CMD specification is developed in China. Main representative: Sea.js

1. Definition Module

Define (function (Require, exports, module) {
 //via require introduces dependent
 var $ = require (' jquery ');
 var spinning = require ('./spinning ');
 Through exports to provide external interface
 exports.dosomething = ...
 or provide the entire interface
 Module.exports = ...} via Module.exports
;

2. Loading module

Seajs.use (".. /static/hello/src/main ")
Difference:

For dependent modules, AMD is in advance, and CMD is deferred execution. However, Requirejs from 2.0, also changed to be able to delay the execution (different according to the writing, processing different). CMD advocates as lazy as possible.

CMD is highly reliant on proximity, AMD is highly reliant on relying on predecessors.

The above is the entire content of this article, I hope to help you learn.

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.