js模块规范

 1 //CommonJS模块规范,
 2 //每个模块存在着require、exports、module 这3个变量,nodejs对获取的js文件内容进行了头尾包装    
 3 (function (exports, require, module, __filename, __dirname) { 
 4   var math = require('math'); 
 5   exports.area = function (radius) { 
 6     return Math.PI * radius * radius; 
 7   }; 
 8 }); 
 9  
10 //AMD(Asynchronous Module Definition)规范是CommonJS规范延伸,
11 //https://github.com/amdjs/amdjs-api/wiki/AMD
12 //模块定义如下define(id?, dependencies?, factory); 它的模块id和依赖是可选的,
13 //第一个参数 id 为字符串类型,表示了模块标识,为可选参数。若不存在则模块标识应该默认定义为在加载器中被请求脚本的标识。如果存在,那么模块标识必须为顶层的或者一个绝对的标识。
14 //第二个参数,dependencies ,是一个当前模块依赖的,已被模块定义的模块标识的数组字面量。
15 //第三个参数,factory,是一个需要进行实例化的函数或者一个对象。
16  
17 //创建模块标识为 alpha 的模块,依赖于 require, export,和标识为 beta 的模块  
18 define("alpha", [ "require", "exports", "beta" ], function( require, exports, beta ){
19     export.verb = function(){
20         return beta.verb();
21         // or:
22         return require("beta").verb();
23     }
24 });
25 
26 //一个返回对象字面量的异步模块
27 define(["alpha"], function( alpha ){
28     return {
29         verb : function(){
30             return alpha.verb() + 1 ;
31         }
32     }
33 });
34  
35 //无依赖模块可以直接使用对象字面量来定义
36 define( {
37     add : function( x, y ){
38         return x + y ;
39     }
40 } );
41  
42 //类似与 CommonJS 方式定义
43 define( function( require, exports, module){
44     var a = require('a'),
45          b = require('b');
46  
47     exports.action = function(){};
48 } );
49  
50 define(function() { 
51   var exports = {}; 
52   exports.sayHello = function() { 
53     alert('Hello from module: ' + module.id); 
54   }; 
55   return exports; 
56 });  
57  
58 define(['dep1', 'dep2'], function (dep1, dep2) { 
59   return function () {}; 
60 }); 
61  
62  
63 //CMD(Common Module Definition)规范
64 define(function(require, exports, module) { 
65   // The module code goes here 
66 }); 
67  
68 兼容多种模块规范
69  ;(function (name, definition) { 
70   // 检测上下文环境是否为AMD或CMD 
71   var hasDefine = typeof define === 'function', 
72     //  检查上下文环境是否为Node 
73     hasExports = typeof module !== 'undefined' && module.exports; 
74  
75   if (hasDefine) { 
76     //  AMD环境或CMD环境 
77     define(definition); 
78   } else if (hasExports) { 
79     //  定义为Node模块 
80     module.exports = definition(); 
81   } else { 
82     //  将模块的执行结果挂在window变量中,在浏览器中this指向window 对象 
83     this[name] = definition(); 
84   } 
85 })('hello', function () { 
86   var hello = function () {}; 
87   return hello; 
88 }); 
原文地址:https://www.cnblogs.com/godghdai/p/6917149.html