What is the difference between the AMD specification and the CMD specification?
Before we compare, we have to understand what is the AMD specification? What is the CMD specification? Of course, first of all, I am a summary of the next, but also on-line to see the information, their own summary or can be said to tidy up, for everyone to understand more in depth! Because we all know the AMD specification: is REQUIREJS in the promotion process of the module definition of the normalized output, and the CMD specification: Seajs in the promotion process of the module definition of the normalized output.
What is the CMD specification?
in cmd, a module is a file, as shown in the following code:
The basic format is as follows: Define (ID, deps, Factory)//such as the following code define (' Hello ', [' JQuery '],function (Require, exports, module) { //module code} );
Define is a global function that is mainly used to set the module. Where the ' Hello ' is the module name, [' jquery '] is a dependency, you can also rely on multiple items can be written as follows [' jquery ', ' ', '] separated by commas, where the above ID (module name) and Deps (dependent) can be omitted. When omitted, then the module name is the file name. For example, I have a file called A.js, then I define the module as shown in the following code:
Define (function (Require, exports, module) { //Modules code});
So if I want to rely on a.js in the B.js code, then I can write this directly:
Define (function (Require,exports,module) {var a = require (' A ')});
Note, however, that ID and deps are not part of the CMD specification. So in Seajs the general wording is not with the module name and dependencies. is the code format as above.
Here's a look at factory in Seajs factory can be either a function, an object, or a string. Factory is the object string, the interface that represents the module is the object or string, as follows to define a JSON object.
Define ({"AA": ' BB '}), similar to the JSONP format, but this data object is highly available, and because it is a static object, he is also CDN-friendly, can improve performance, for example, we have a provincial and municipal district so a JSON format to return to our front-end, If provided to the client in the form of a traditional JSONP, it must provide a callback function name that dynamically generates the return data based on the name of the functor, which makes the standard JSONP data necessarily not CDN-friendly. So we can use this format
Define ({ provinces: [ { name: ' Shanghai ', areas: [' Pudong New Area ', ' Xuhui ']}, { name: ' Jiangsu ', cities: [' Nanjing ' , ' Nantong ']} //... });
Assuming that this file is named China.js, then if a module needs this data, it only needs to:
Define (function (Require,exports,module) {
var China = require ('./china '); Use Chinese provincial and municipal data here});
When factory is a function, it represents the construction method of the module, and the construction method can be used to get the interface provided by the module. By default, three parameter require,exports,module are passed in. So let's take a look at the Require parameter!
Require
Require is a method by which he can resolve dependencies to get interfaces provided by other modules, such as the following A.js code:
Define (function (require, exports) {
EXPORTS.A = function () {
A lot of code
};
});
So now I want to invoke the A method inside the b.js inside the a.js. We can do the following:
Define (function (Require,exports) {
var fun = require ('./a ');
Console.log (Fun.a ()); You can invoke and execute the a function.
})
Require.async (id,callback): Require.async: Method is used to load the module asynchronously inside the module and execute the specified callback after the load is complete. The callback parameter is optional. For example, the following code:
Define (function (Require, exports, module) { //asynchronously loads a module that executes a callback Require.async ('./b ') when loading is complete, and function (b) { B.dosomething (); }); Asynchronously loads multiple modules, executes the callback require.async (['./C ', './d '], and function (d) { c.dosomething () when loading is complete; D.dosomething (); });
Note: The require is performed synchronously, while Require.async is the asynchronous callback execution.
Require.resolve (ID)
Use the path resolution mechanism inside the module system to parse and return the module path. The function does not load the module and returns only the resolved absolute path.
Define (function (require, exports) { Console.log (require.resolve ('./b ')); ==> http://example.com/path/to/b.js});
Exports
Exports: is an object that is used to provide a module interface to the outside.
For example, the above code: the following a.js inside
Define (function (require, exports) { EXPORTS.A = function () { //A lot of code };});
or write as follows:
Define (function (require, exports) { return { I: ' A ', a:function () { //execute the corresponding code }} );
So if I want to call a.js inside the A method in B.js, because A.js uses exports to provide an interface a method, then in b.js we just need to first such var fun = require ('./a '); then execute Fun.a (); You can execute the a method.
Module
The module is an object that stores some of the properties and methods associated with the current module. whichexports是module.exports的一个引用。
moudle.id
模块的唯一标识。如下代码:
Define(' id 'function(requireexportsmodule/Code });
Module.uri
The absolute path of the module is obtained according to the path parsing rules of the module system.
Define(function(requireexportsmoduleconsole. Log(module. URI//==> http://example.com/path/to/this/file.js});
And so on the specific properties can be seen Seajs official website. The principle is the same because Seajs also uses the CMD specification.
What is the AMD specification?
such as Xia Guan Network code:
Define ("Alpha", ["require", "exports", "beta"], function (require, exports, beta) { exports.verb = function () { R Eturn Beta.verb (); Or: return require ("beta"). verb (); }});
The Require function here allows you to rely on a module at any time to obtain a reference to the module, so that even if the module is not defined as a parameter, it can be used, and exports is the entity of the defined Alpha module, and any properties and methods defined on it are the properties and methods of the Alpha module. by Exports.verb = ... is to define a verb method for the Alpha module. In the example is a simple call to the module beta verb method.
The above module names and dependencies can also be omitted, then if omitted, then we can call them anonymous functions, then the same module name is the file name and the above CMD specification is similar. The above [', ' '] parameter represents a set of dependencies that must be made on the defined module. The third parameter (' definition function ') is a function that performs initialization for your module. One of the simplest modules can be defined in the following way:
module-defined functions//dependencies (foo and bar) are mapped as parameters of the function define (' Mymoudle ', [' foo ', ' Bar '],function (foo,bar) { ///Return a value that defines the module's export interface /// (that is, the function we want to call after exporting) //Create the module var mymodule = { dostuff:function () { console.log (' yay! Stuff '); } } return mymodule;});
You can also write this:
Another example could be ... define (' MyModule ', [' Math ', ' graph '], function (math, graph) { //Note that this is a slightly different model from AMD, but in several different ways
//to define the module is also possible, because the syntax in some ways is still more flexible return { plot:function (x, y) { return Graph.drawpie (Math.randomgrid (x, y));}}; });
require , on the other hand, is primarily used to load code in the top-level JavaScript file or in the case of dynamic read dependencies. An example of usage is as follows:
Assuming that ' foo ' and ' bar ' are two external modules///In this case, the two modules loaded with ' exports ' are passed as two parameters to the callback function//So you can access them require ([' foo ', ' bar '], function ( Foo, bar) { //here Write the rest of the code foo.dosomething ();});
dynamically loaded dependencies include the following code:
Define (function (require) { var isReady = false, foobar; Note that within the module definition internally inline require statement require ([' foo ', ' bar '], function (foo, bar) { IsReady = true; Foobar = foo () + bar (); }); We can still return a module return { isready:isready, Foobar:foobar };});
The difference between the CMD specification and the AMD specification is as follows:
1. Cmd depends on the nearest: code like the following
Define (function (require,exports,module) { var a = require ('./a '); A.dosomthing (); });
code at run time, the first is not aware of dependencies, you need to traverse all the Require keyword to find out the dependencies behind. This is done by using the function ToString to match the dependency after the Require keyword.
AMD relies on pre-built: The following code:
define (['./a ', './b '],function (A, b) { //... A.dosomthing (); //...... B.dosomthing (); })
The code is immediately aware of dependencies once it runs here. Instead of traversing the entire function body to find its dependencies, performance is improved, and the downside is that developers have to explicitly indicate dependency-which can make the development effort larger, such as: When dependencies are N-time, they are more annoying and error-prone. However, starting from 2.0, Requirejs is also changed to be deferred (depending on the way it is written and handled differently).
2. In order of execution:
CMD is deferred and AMD is executed in advance.
3. API Design Angle :
AMD's API defaults to one when multiple uses , the CMD API is strictly differentiated, advocating a single responsibility . For example, AMD, require global require and local require, are called require. In CMD, there is no global require, but according to the completeness of the module system, provide seajs.use to realize the loading and starting of the module system. CMD, each API is simple and pure .
What is the difference between the AMD specification and the CMD specification?