Skip to content

Instantly share code, notes, and snippets.

@fwon
Created August 24, 2014 08:00
Show Gist options
  • Save fwon/9d7c41e11fcc86c346ce to your computer and use it in GitHub Desktop.
Save fwon/9d7c41e11fcc86c346ce to your computer and use it in GitHub Desktop.
类库开发--兼容多种模块的代码
兼容多种模块规范代码(Node, AMD, CMD以及常见浏览器环境):
;(function(name, definition) {
//检测上下文环境是否为AMD或CMD
var hasDefine = typeof define === 'function',
//检测上下文环境是否为Node
hasExports = typeof module !== 'undefined' && module.exports;
if (hasDefine) {
//AMD环境或CMD环境
define(definition);
} else if (hasExports) {
//定义为普通Node模块
module.exports = definition();
} else {
//将模块的执行结果挂在window变量中,在浏览器中this指向window对象
this[name] = definition();
}
})('hello', function() {
var hello = function() {};
return hello;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment