如果你定義一個循環依賴關系 (a 依賴b 並且 b 依賴 a),那么當b的模塊構造函數被調用的時候,傳遞給他的a會是undefined。 但是b可以在a模塊在被引入之后通過require(‘a’)來獲取a (一定要把require作為依賴模塊,RequireJS才會使用正確的 context 去查找 a):
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()的方式吧。
如果你熟悉 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 });