变量使用es6模块引入与传统引入对比
2020-04-03 本文已影响0人
John_Phil
使用传统方式引入
aaa.js
var a=10;
setTimeout(function() {a=20}, 1000);
bbb.js
function b(){
console.log(a)
setTimeout(function() {console.log(a)}, 1000);
}
test.html
<script src="aaa.js"></script>
<script src="bbb.js"></script>
<script>
b();
</script>

使用es6模块引入
aaa.js
var a=10;
setTimeout(function() {a=20}, 1000);
export {a}
bbb.js
import { a } from "./aaa.js";
function b(){
console.log(a)
setTimeout(function() {console.log(a)}, 1000);
}
export{a,b};
test.html
<script type="module">
import {a,b } from "./bbb.js";
b();
</script>

es6模块化引入可以避免很多不必要的麻烦
传统的引入方式 变量a 定义在前,后续都会使用 a变量
而使用模块导入 a变量在aaa模块中, 如果不引入到b中 b是无法访问。
可以使我们的变量指向更明确。
比如
aaa.js
var a=10;
setTimeout(function() {a=20}, 1000);
export {a}
bbb.js
function b(){
console.log(a)
setTimeout(function() {console.log(a)}, 1000);
}
export{b};
test.html
<script type="module">
import { a } from "./aaa.js";
import { b } from "./bbb.js";
b();
</script>
