Home  >  Q&A  >  body text

javascript - Two js files require each other

As for the written test questions I encountered today, please give me some answers.
A.js and b.js require each other, will they fall into an infinite loop? Can the results be exported? How to avoid this problem?

学习ing学习ing2642 days ago787

reply all(2)I'll reply

  • 迷茫

    迷茫2017-06-28 09:30:31

    This is to examine the cyclic loading of JavaScript modules
    You can use the module mechanism of es6 to get around this problem. ES6's handling of "cyclic loading" is fundamentally different from CommonJS. ES6 doesn't care at all whether "loop loading" occurs, it just generates a reference to the loaded module. The developer needs to ensure that the value can be obtained when the value is actually obtained.

    reply
    0
  • PHP中文网

    PHP中文网2017-06-28 09:30:31

    If you understand it literally, only use

    var b = require('b')

    Then this problem can be understood as a circular reference problem in CommonJS. CommonJS's approach is that once a module is "loop loaded", only the executed part will be output, and the unexecuted part will not be output.

    If you understand the circular reference between two modules conceptually, it also involves the module reference of es6.

    import b from 'b'

    ES6 does not care at all whether "loop loading" occurs, it just generates a reference to the loaded module. The developer needs to ensure that the value can be obtained when the value is actually obtained.

    Simply using CommonJs or simply using esm (es6 module) will not cause an infinite loop. But it can happen if you mix the two.

    I recommend Ruan Yifeng’s blog, which is very well written.
    http://www.ruanyifeng.com/blo...

    reply
    0
  • Cancelreply