Skip to content

Instantly share code, notes, and snippets.

@leohxj
Created April 16, 2014 04:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leohxj/10807844 to your computer and use it in GitHub Desktop.
Save leohxj/10807844 to your computer and use it in GitHub Desktop.
从knockoutjs源码中读到了一个很好的能兼容AMD,commonjs规范的模块定义。
//闭包执行一个立即定义的匿名函数
!function(factory) {
//factory是一个函数,下面的koExports就是他的参数
// Support three module loading scenarios
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
// [1] CommonJS/Node.js
// [1] 支持在module.exports.abc,或者直接exports.abc
var target = module['exports'] || exports; // module.exports is for Node.js
factory(target);
} else if (typeof define === 'function' && define['amd']) {
// [2] AMD anonymous module
// [2] AMD 规范
//define(['exports'],function(exports){
// exports.abc = function(){}
//});
define(['exports'], factory);
} else {
// [3] No module loader (plain <script> tag) - put directly in global namespace
factory(window['ko'] = {});
}
}(function(koExports){
//ko的全局定义 koExports是undefined 对应着上面的[3] 这种情况
var ko = typeof koExports !== 'undefined' ? koExports : {};
//定义一个ko的方法
ko.abc = function(s){
alert(s);
}
});
//[3]中情况的调用
ko.abc("msg");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment