Due to the circular reference, when require.js loads “b” as a prerequisite for “a”, it cannot return the value “a” because initModule() has not yet been called. However, by the time b.somethingElse() called, module "a" was initialized, and the call to require("a") would return.
The following code shows that inside both modules, the order in which they are loaded does not matter. I slightly modified it from the require.js example to make it more obvious.
// Inside a.js: define(["require", "b"], function initModule(require) { return { doSomehingWithA: function() { ...}, doSomethingElse: function(title) { // by the time this function is called, // require("b") will properly resolve return require("b").doSomethingWithB(); } } } ); // Inside b.js: define(["require", "a"], function initModule(require) { return { doSomethingWithB: function() {...}, doSomethingElse: function(title) { // by the time this function is called, // require("a") will properly resolve return require("a").doSomethingWithA(); } }; } );
By the way, while circular links are generally a symptom of poor design, this is not always the case. For example, I implemented a factory widget module, which, among other things, referenced the container-widget module, which then had to reference the factory in order to create its content. Completely legal.
source share