极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# Node 中循环引用会发生什么

Issue

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

Author

回答者: mrrs878 (opens new window)

在 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

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

Author

回答者: mrrs878 (opens new window)

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

Last Updated: 11/27/2021, 6:11:48 PM