Skip to content

Instantly share code, notes, and snippets.

@yangfch3
Last active October 12, 2016 04:12
Show Gist options
  • Save yangfch3/b3e736ac7318dd6cf8f9d3fe23bccf90 to your computer and use it in GitHub Desktop.
Save yangfch3/b3e736ac7318dd6cf8f9d3fe23bccf90 to your computer and use it in GitHub Desktop.
ES6 模块循环依赖
/**
* ES6 模块循环依赖时
* 代码的运行过程与 CommonJS 一致
* 不同的是变量引用的处理不同
* ES6加载的变量,都是动态引用其所在的模块。只要引用存在,代码就能执行。
*/
/**
* module-a.js
*/
import { bar } from './module-b.js';
console.log(bar);
// 换一种写法:export var foo = function(){...}
// 换一种写法:export let foo = function(){...}
// 会得到不同的结果,初步判定这与提升与否有关
export function foo() {
console.log('foo');
bar();
console.log('foo 执行完毕');
}
foo();
console.log(bar);
/**
* module-b.js
*/
import { foo } from './module-a.js';
console.log(foo);
// 换一种写法:export var bar = function(){...}
// 换一种写法:export let bar = function(){...}
// 会得到不同的结果,初步判定这与提升与否有关
export function bar() {
console.log('bar');
if (Math.random() < 0.5) {
foo();
}
console.log('bar 执行完毕');
}
console.log(foo);
/**
* 执行
*/
/**
> $ babel-node a.js
[Function: foo]
[Function: foo]
[Function: bar]
foo
bar
foo
bar
bar 执行完毕
foo 执行完毕
bar 执行完毕
foo 执行完毕
[Function: bar]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment