Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CommonJS循环加载 #199

Open
TieMuZhen opened this issue May 10, 2022 · 0 comments
Open

CommonJS循环加载 #199

TieMuZhen opened this issue May 10, 2022 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

题目

a.jsb.jsc.js三个文件如下,求执行node a.js输出结果

a.js代码如下

const b = require('./b.js');
console.log(exports.x);
exports.x = 'x';
require('./c.js');

b.js代码如下

const a = require('./a.js');
console.log(a);
console.log(a.x);
a.x='y';

c.js代码如下

const a = require('./a.js');
console.log(a.x);

输出结果如下

{}
undefined
y
x

原理

CommonJS中的做法是,一旦某个模块被”循环引用“,也就是这个模块没有加载完,就进入了循环,所以原则是,只exports已经执行的那部分,没执行的不输出。

详细原理请阅读阮一峰大佬的JavaScript 模块的循环加载

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant