如果您定义了一个循环依赖项(“a”需要“b”和“b”需要“a”),那么在这种情况下,当“b”的模块函数被调用时,它将得到“a”的未定义值。“b”可以在模块被定义为使用require()方法之后获取“a”(请确保指定需要作为依赖项,以便使用正确的上下文查找“a”):
//Inside b.js:
define(["require", "a"],
function(require, a) {
//"a" in this case will be null if "a" also asked for "b",
//a circular dependency.
return function(title) {
return require("a").doSomething();
}
}
);
通常,您不需要使用require()来获取模块,而是依赖于将模块传递给函数作为参数。循环依赖是很少见的,通常是您可能想要重新考虑设计的标志。然而,有时它们是必需的,在这种情况下,使用require()如上所述。
如果您熟悉CommonJS模块,则可以使用导出来为模块创建一个空对象,该对象可立即用于其他模块的引用。通过在循环依赖项的两边执行这个操作,您就可以安全地保留到另一个模块。这只有在每个模块向模块值导出对象时才有效,而不是函数:
//Inside b.js:
define(function(require, exports, module) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
var a = require("a");
exports.foo = function () {
return a.bar();
};
});
或者,如果您正在使用依赖数组方法,请要求特殊的“导出”依赖项:
//Inside b.js:
define(['a', 'exports'], function(a, exports) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
exports.foo = function () {
return a.bar();
};
});
原文链接:http://requirejs.org/docs/api.html#circular