Last active
October 12, 2016 03:42
-
-
Save yangfch3/19ec68448a99af6865e760c96ee4d2fe to your computer and use it in GitHub Desktop.
CommandJS 循环依赖实例讲解
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 一段代码分析 CommandJS 的循环依赖 | |
* | |
* 一句话概括:出现循环依赖时,循环依赖的后者只会获取前者已执行部分的 exports | |
*/ | |
// a.js | |
exports.done = false; | |
var b = require('./b.js'); // 2. 出现 require,自身暂停执行,开始执行 b.js | |
console.log('在 a.js 之中,b.done = %j', b.done); // 5. b.js 执行完毕后,a.js 继续往下执行 | |
exports.done = true; | |
console.log('a.js 执行完毕'); | |
// b.js | |
exports.done = false; | |
var a = require('./a.js'); // 3. 发生循环依赖,a.js 还没有执行完,从 a.js **已执行完的部分** 的获取 exports | |
console.log('在 b.js 之中,a.done = %j', a.done); // 4. b 继续往下执行 | |
exports.done = true; | |
console.log('b.js 执行完毕'); | |
// main.js | |
var a = require('./a.js'); // 1. 开始执行 a.js | |
var b = require('./b.js'); // 6. b.js 已经执行过,直接获取其缓存的 exports | |
console.log('在 main.js 之中, a.done=%j, b.done=%j', a.done, b.done); // 7. output | |
/** | |
> $ node main | |
在 b.js 之中,a.done = false | |
b.js 执行完毕 | |
在 a.js 之中,b.done = true | |
a.js 执行完毕 | |
在 main.js 之中, a.done=true, b.done=true | |
*/ | |
/** | |
a ↓ | |
↓ → b ↓ | |
↓ | |
↓ | |
↓ ← ← ↓ done | |
↓ done | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment