高级前端
node
【Q289】Node 中循环引用会发生什么

Node 中循环引用会发生什么

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 291 (opens in a new tab)

Author 回答者: mrrs878 (opens in a new tab)

在 CommonJS 规范中,当遇到require()语句时,会执行require模块中的代码,并缓存执行的结果,当下次再次加载时不会重复执行,而是直接取缓存的结果。正因为此,出现循环依赖时才不会出现无限循环调用的情况。

// a.js
const { b } = require("./b");
 
const a = 11;
 
console.log("b in a.js", b);
 
module.exports = { a };
// b.js
const { a } = require("./a");
 
const b = 12;
 
console.log("a in b.js", a);
setTimeout(() => {
  console.log("a in b.js", a);
}, 1000);
 
module.exports = { b };

当执行node a.js时:

a in b.js is undefined
b in a.js is 12
(node:23352) Warning: Accessing non-existent property 'a' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
a in b.js is undefined

Author 回答者: shfshanyue (opens in a new tab)

@mrrs878 在 b.js 代码示例中有一个拼写错误

Author 回答者: mrrs878 (opens in a new tab)

@shfshanyue 感谢老哥指正,已修改