我正在使用以下闭包模式来模块化我的代码:
(function(root) {
// MODULE CODE HERE
if (typeof module !== 'undefined' && module.exports) { // CommonJS
/* var dependencies = require(...) */
module.exports = myModule;
} else if (typeof define !== 'undefined' && define.amd) { // AMD
/* var dependencies...; */
define([/* dependencies */], function(/* dependencies */) {
/* Assign closure level vars to respective arguments */
return myModule;
});
} else {
// Dependencies??
root.myModule = myModule;
}
})(this);
即,我们使用特征检测来支持CommonJS模块(例如node.js),AMD或基本全局命名空间实例化。
这在node.js中运行良好;但如果模块有任何依赖项,则在浏览器中失败。也就是说,假设myModule引用了在不同模块中定义的内容:例如,假设我有super.js和child.js,具有相应的模块定义,如上所述,其中super.js创建一个名为root.super的函数(在浏览器中,root === window),如果child.js尝试执行super(),我将得到类似“super is not a function”的错误消息。
这是怎么回事呢?
为了尝试解决它,我更改了在
this
被别名为root
的情况。在浏览器中,this
指的是window
,但在服务器(node.js)中,this
指的是global
。使用root
的别名可以使模块在客户端和服务器端都能够使用。 - zzzzBovthis
可以是任何东西。 - Amberlamps