阅读requireJs文档,
为了修复循环依赖,建议使用 exports
为模块创建一个空对象,该对象可立即供其他模块引用。
我试过这段代码,但它似乎不起作用。怎么了?
附言:
阅读评论以查看输出,
特别是 setTimeout 调用中的 B 模块。
// A module
define([
'b'
], function (b) {
console.log('B:', b); // B, Object
var A = {
boo: 1
};
return A;
});
// B module
define([
'a',
'exports'
], function (a, exports) {
console.log('A:', a); // A, undefined (as I was expecting)
exports.A = function () {
return a;
}
var B = {
bar: 1
};
setTimeout(function () {
console.log('exports.A', exports.A()); // exports.A undefined
// I would like to access the A object
// which is defined in A module
}, 500);
return B;
});
// main.js
(function () {
define([
'a'
], function () {
});
}());
最佳答案
您应该能够在 B 模块中使用 require()
的同步版本来访问“A”模块:
// B module
define([
'a',
'exports'
], function (a, exports) {
console.log('A:', a); // A, undefined (as I was expecting)
exports.A = function () {
return require('a');
}
...
});
关于javascript - 使用 requireJs 的模块中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11264827/