若是你定义一个循环依赖关系 (a 依赖b 而且 b 依赖 a),那么当b的模块构造函数被调用的时候,传递给他的a会是undefined。 可是b能够在a模块在被引入以后经过require(‘a’)来获取a (必定要把require做为依赖模块,RequireJS才会使用正确的 context 去查找 a):git
1 //Inside b.js: 2 define(["require", "a"], 3 function(require, a) { 4 //"a" in this case will be null if a also asked for b, 5 //a circular dependency. 6 return function(title) { 7 return require("a").doSomething(); 8 } 9 } 10 );
一般状况下,你不该该使用require()的方式来获取一个模块,而是使用传递给模块构造函数的参数。循环依赖很罕见,一般代表,你可能要从新考虑这一设计。然而,有时须要这样用,在这种状况下,就使用上面那种指定require()的方式吧。github
若是你熟悉 CommonJS 模块的写法,你也可使用 exports 建立一个空对象来导出模块,这样定义的模块能够被其余模块当即使用。即便在循环依赖中,也能够安全的直接使用。 不过这只适用于导出的模块是对象,而不是一个函数:数组
1 //Inside b.js: 2 define(function(require, exports, module) { 3 //If "a" has used exports, then we have a real 4 //object reference here. However, we cannot use 5 //any of a's properties until after b returns a value. 6 var a = require("a"); 7 8 exports.foo = function () { 9 return a.bar(); 10 }; 11 });
用依赖数组的话,记得将 'exports'看成依赖模块:安全
1 //Inside b.js: 2 define(['a', 'exports'], function(a, exports) { 3 //If "a" has used exports, then we have a real 4 //object reference here. However, we cannot use 5 //any of a's properties until after b returns a value. 6 7 exports.foo = function () { 8 return a.bar(); 9 }; 10 });