JavaScript模块详解(9)
注意事项
1、声明的变量,对外都是只读的。但是导出的是对象类型的值,就可修改。
2、导入不存在的变量,值为undefined。
ES6 中的循环引用
ES6 中,imports 是 exprts 的只读视图,直白一点就是,imports 都指向 exports 原本的数据,比如:
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can't be changed
counter++; // TypeError
因此在 ES6 中处理循环引用特别简单,看下面这段代码:
//------ a.js ------
import {bar} from 'b'; // (1)
export function foo() {
bar(); // (2)
}
//------ b.js ------
import {foo} from 'a'; // (3)
export function bar() {
if (Math.random()) {
foo(); // (4)
}
}
假设先加载模块 a,在模块 a 加载完成之后,bar 间接性地指向的是模块 b 中的 bar。无论是加载完成的 imports 还是未完成的 imports,imports 和 exports 之间都有一个间接的联系,所以总是可以正常工作。
实例
//---module-B.js文件---
//导出变量:name
export var name = "cfangxu";
moduleA模块代码:
//导入 模块B的属性 name
import { name } from "./module-B.js";
console.log(name)
//打印结果:cfangxu
批量导出
//属性name
var name = "cfangxu";
//属性age
var age = 26;
//方法 say
var say = function(){
console.log("say hello");
}
//批量导出
export {name,age,say}
批量导入
//导入 模块B的属性
import { name,age,say } from "./module-B.js";
console.log(name)
//打印结果:cfangxu
console.log(age)
//打印结果:26
say()
//打印结果:say hello
重命名导入变量
import {name as myName} from './module-B.js';
console.log(myName) //cfangxu
整体导入
/使用*实现整体导入 import * as obj from "./module-B.js"; console.log(obj.name) //结果:"cfangxu" console.log(obj.age) //结果:26 obj.say(); //结果:say hello
