一下三块均以 foo.js 为示例文件名,以 jQuery,underscore 为需求组件
ADM:异步模块规范, RequireJs 的支持格式
1 // 文件名: foo.js 2 define(['jquery', 'underscore'], function ($, _) { 3 // 方法 4 function a(){}; // 私有方法,因为没有被返回(见下面) 5 function b(){}; // 公共方法,因为被返回了 6 function c(){}; // 公共方法,因为被返回了 7 // 暴露公共方法 8 return { 9 b: b, 10 c: c 11 } 12 });
CommonJs:node 的支持格式
1 // 文件名: foo.js 2 var $ = require('jquery'); 3 var _ = require('underscore'); 4 5 // methods 6 function a(){}; // 私有方法,因为它没在module.exports中 (见下面) 7 function b(){}; // 公共方法,因为它在module.exports中定义了 8 function c(){}; // 公共方法,因为它在module.exports中定义了 9 10 // 暴露公共方法 11 module.exports = { 12 b: b, 13 c: c 14 };
UMD:通用模式,支持以上两种格式,切可以支持老式的 “全局变量” 规范
1 (function (root, factory) { 2 if (typeof define === 'function' && define.amd) { 3 // AMD 4 define(['jquery', 'underscore'], factory); 5 } else if (typeof exports === 'object') { 6 // Node, CommonJS之类的 7 module.exports = factory(require('jquery'), require('underscore')); 8 } else { 9 // 浏览器全局变量(root 即 window) 10 root.returnExports = factory(root.jQuery, root._); 11 } 12 }(this, function ($, _) { 13 // 方法 14 function a(){}; // 私有方法,因为它没被返回 (见下面) 15 function b(){}; // 公共方法,因为被返回了 16 function c(){}; // 公共方法,因为被返回了 17 18 // 暴露公共方法 19 return { 20 b: b, 21 c: c 22 } 23 }));
原文地址:http://web.jobbole.com/82238/