First, let's take a look at the code, each of which actually represents a JS file. So the following is actually a three JS file. The first one is the main file that we want to run, and the next two are A, b files.
From above you can read a, b two modules referencing each other, the above output results are as follows:
So how does that make sense?
First look at the main module, first output main starting; The A module is then called;
Then we enter the A module, first output a starting; Then the B module is called;
Then we go into the B module, first output B starting; Then call a module;
But the problem is, a module has not been initialized well, so a module will return a unfinished copy, you can understand to return an empty object {};
However, a module in the reference to the B module, the front of a exports.done = flase;
This is not the same, at this time is not an empty object, but {done:flase}; But if it is an empty object, it will output undefined;
So output in B, A.done = Flase , then run the B module until the last output b.done ;
Then a module starts to run down, output in A, B.done = True, because the last B module output is done=true AH;
Then output A.done ; A module is finished running.
To this, a, b two modules are loaded, in main although there is a reference to the B module, but will not be executed.
And then the last thing we see is the output in Main, A.done=true, B.done=true.
variants
We change the statement of a, B module as follows:
We removed two of the lines of the black line, and now what does the output turn out to be?
Please see:
Here is not carefully analyzed, left to you to analyze.
A detailed explanation of the loop invocation problem for modules in node. js