一、基本格式
1 ;(function(undefined) { 2 "use strict" 3 var _global; 4 5 var plugin = { 6 add: function(n1,n2){ return n1 + n2; },//加 7 sub: function(n1,n2){ return n1 - n2; },//减 8 mul: function(n1,n2){ return n1 * n2; },//乘 9 div: function(n1,n2){ return n1 / n2; } //除 10 } 11 12 // 最后将插件对象暴露给全局对象 13 _global = (function(){ return this || (0, eval)('this'); }()); 14 15 // 判断是否存在加载器 存在就使用加载器 不存在就使用全局对象 16 if (typeof module !== "undefined" && module.exports) { 17 module.exports = plugin; // cmd 加载 18 } else if (typeof define === "function" && define.amd) { 19 define(function(){return plugin;}); // amd 加载 20 } else { 21 !('plugin' in _global) && (_global.plugin = plugin); // 全局加载 22 } 23 }());
二、常用工具函数
1、对象合并

1 function extend(o,n,override) { 2 for(var key in n){ 3 if(n.hasOwnProperty(key) && (!o.hasOwnProperty(key) || override)){ 4 o[key]=n[key]; 5 } 6 } 7 return o; 8 }
2、自定义模版引擎

1 function templateEngine(html, data) { 2 var re = /<%([^%>]+)?%>/g, 3 reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 4 code = 'var r=[]; ', 5 cursor = 0; 6 var match; 7 var add = function(line, js) { 8 js ? (code += line.match(reExp) ? line + ' ' : 'r.push(' + line + '); ') : 9 (code += line != '' ? 'r.push("' + line.replace(/"/g, '\"') + '"); ' : ''); 10 return add; 11 } 12 while (match = re.exec(html)) { 13 add(html.slice(cursor, match.index))(match[1], true); 14 cursor = match.index + match[0].length; 15 } 16 add(html.substr(cursor, html.length - cursor)); 17 code += 'return r.join("");'; 18 return new Function(code.replace(/[ ]/g, '')).apply(data); 19 }