Javascript modular programming, javascript modular _ PHP Tutorial

Source: Internet
Author: User
Javascript modular programming (reproduced) and javascript modular. Javascript modular programming (reproduced), javascript modular Javascript modular programming author: Ruan Yifeng release Time: 2013-01-0818: 04 read: 7632 recommendations: 40 original article link [favorites] f javascript modular programming (reproduced), javascript modular
Javascript modular programming author: Ruan Yifeng Release date: read: 7632 recommendations: 40 original article link [favorites]

Function m1 () {//...} function m2 (){//...}

The above functions m1 () and m2 () form a module. You can call it directly.

The disadvantage of this approach is obvious: "contaminated" global variables, cannot ensure that there is no conflict with other modules variable names, and there is no direct relationship between Module members.

  II. object writing

To solve the preceding disadvantages, you can write the module as an object. all Module members are placed in this object.

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

The above functions m1 () and m2 () are encapsulated in the module1 object. When used, the property of this object is called:

module1.m1(); 

However, this write method exposes all Module members and the internal status can be changed externally. For example, external code can directly change the internal counter value.

module1._count = 5; 

  3. execute function writing immediately

You can use Immediately-Invoked Function Expression (IIFE) to avoid exposing private members.

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

Using the above code, external code cannot read the internal _ count variable.

console.info (module1._count); //undefined

Module1 is the basic writing method of the Javascript module. Next, we will process this writing method.

  IV. zoom-in mode

If a module is large, it must be divided into several parts, or a module must inherit from another module, it is necessary to adopt the "amplification mode" (augmentation ).

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

The code above adds a new method m3 () for the module1 module, and then returns the new module1 module.

  5. Loose augmentation)

In the browser environment, each part of the module is usually obtained from the Internet, and sometimes cannot know which part will be loaded first. If you use the method described in the previous section, the first part of the execution may load a non-null object. in this case, you must use the "wide amplification mode ".

var module1 = ( function (mod){  //...  return mod;})(window.module1 {}); 

Compared with "zoom in mode", "wide zoom in mode" means that the parameter of "immediate function execution" can be a null object.

  6. enter global variables

Independence is an important feature of the module. it is best not to directly interact with other parts of the program within the module.

To call global variables within the module, other variables must be explicitly input to the module.

var module1 = (function ($, YAHOO) {  //...})(jQuery, YAHOO); 

The above module1 module needs to use the jQuery library and YUI Library, and the two libraries (actually two modules) are used as the parameter input module1. In addition to ensuring the independence of modules, this also makes the dependency between modules obvious. For more information, see Ben Cherry's famous article JavaScript Module Pattern: In-Depth.

Var math = require ('math ');

Then, you can call the method provided by the module:

var math = require ('math');math.add (2,3); // 5 

Because this series mainly targets browser programming and does not involve node. js, we will not introduce CommonJS much. We only need to know here that require () is used to load modules.

  9. browser environment

With the server module, you naturally want the client module. It is better to be compatible with the two. a module can run on both the server and the browser without modification.

However, due to a major limitation, the CommonJS specification is not applicable to the browser environment. Or the code in the previous section. if you run it in a browser, there will be a big problem. can you see it?

var math = require ('math');math.add (2, 3); 

The second line of Math. add (2, 3) runs after the first line of require ('math'). Therefore, the math. js load must be completed. That is to say, if the loading time is long, the whole application will stop there.

This is not a problem on the server, because all modules are stored on the local hard disk and can be loaded synchronously. the wait time is the read time of the hard disk. However, for browsers, this is a big problem, because the modules are placed on the server side, the waiting time depends on the speed of the network, it may take a long time, the browser is in the "false" status.

Therefore, the browser module cannot use synchronous, but can only use asynchronous ). This is the background of the birth of AMD specifications.

  10. AMD

AMD stands for "Asynchronous Module Definition", which means "Asynchronous Module Definition ". The module is loaded asynchronously. the module loading does not affect the execution of the subsequent statements. All statements that depend on this module are defined in a callback function. after loading is complete, the callback function will run.

AMD also uses the require () statement to load modules, but unlike CommonJS, it requires two parameters:

require ([module], callback); 

The first parameter [module] is an array in which the member is the module to be loaded; the second parameter callback is the callback function after successful loading. If you rewrite the previous code to the AMD format, it is as follows:

require (['math'], function (math) {    math.add (2, 3);}); 

Math. add () is not synchronized with the math module, and the browser will not be suspended. Obviously, AMD is suitable for browser environments.

Currently, there are two major Javascript libraries that implement AMD specifications: require. js and curl. js. The third part of this series will introduce require. js to further explain AMD usage and how to put modular programming into practice.

I am using a very popular library require. js.

  1. why use require. js?

At the earliest time, all Javascript code was written in a file. it was enough to load the file. Later, there were more and more code, and one file was not enough. it had to be divided into multiple files and loaded in sequence. I believe many people have seen the following webpage code.

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.