ES6模块化是值的引用()
网上说模块化区别,不少答案是
“commonjs的模块化是值的拷贝,es module的模块化是值的引用。”
自己准备的几个例子,和预期结果还是有区别的。
eg1:
//模块 m.js
const m = {
a:1,
arr:['a','b'],
add(){
m.a=2;
m.arr.push('c')
}
}
export default m;
//调用者
import M from './m';
console.log(M.a,M.arr);
M.add();
console.log(M.a,M.arr);
//输出
//1 (2) ["a", "b"]
//2 (3) ["a", "b", "c"]
eg2:
//模块 m.js
let a= 1;
const arr = ['a','b'];
function add(){
a=2;
arr.push('c')
}
export default {
a,
arr,
add
}//调用者
import M from './m';
console.log(M.a,M.arr);
M.add();
console.log(M.a,M.arr);
//输出
//1 (2) ["a", "b"]
//1 (3) ["a", "b", "c"]
eg3:
//模块 m.js
let a= 1;
const arr = ['a','b'];
function add(){
a=2;
arr.push('c')
}
export {
a,
arr,
add
}//调用者
import * as M from './m';
console.log(M.a,M.arr);
M.add();
console.log(M.a,M.arr);
//输出
//1 (2) ["a", "b"]
//2 (3) ["a", "b", "c"]
【ES6模块化是值的引用()】上面例子2的结果并不符合预期,而且例子2和例子3主要是export 加不加default的区别。
能解释的小伙伴可以评论区留言!
推荐阅读
- 热闹中的孤独
- 我要做大厨
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量
- 爱就是希望你好好活着
- 太平之莲
- 知识
- 叙述作文
- 时间老了
- 清明,是追思、是传承、是感恩。
- 我错了,余生不再打扰