es6导出 哪些是值传递哪些是引用传递

1,513 阅读2分钟

起因

  • 前些日子创建了一个前端技术交流群。今天一个群友在群里分享了一个问题

image.png

  • 我一看就意识到了事情不对,因为这题我不会,甚至都没注意过

image.png

  • 我还是猜了一个答案
  • 不过,猜,不是我的风格,根据群友提供的学习网址,今天又重新学习了一下ES6的模块化

一下内容是我看Jake Archibald的博客后自己理解总结的

导入

// module.js 
export let thing = 'initial'; 
setTimeout(() => { thing = 'changed'; }, 500);
// main.js 
import { thing as importedThing } from './module.js'; 
const module = await import('./module.js'); 
let { thing } = await import('./module.js'); 
setTimeout(() => { 
    console.log(importedThing); // "changed" 
    console.log(module.thing); // "changed" 
    console.log(thing); // "initial" 
}, 1000);

main.js通过普通的方式导入module.js模块时,module.jsthing的改变会同步到mian.js里。但是,

解构不会接受module.js的更改,因为解构相当于重新赋值给了一个标志符

  • 总结一下

image.png

导出

  • 普通导出
export { thing };
export { thing as otherName };

按引用传递

  • 默认导出
// module.js 
let thing = 'initial'; 
export { thing }; 
export default thing; 
setTimeout(() => { thing = 'changed'; }, 500);
// main.js 
import { thing, default as defaultThing } from './module.js'; 
import anotherDefaultThing from './module.js'; 

setTimeout(() => { 
    console.log(thing); // "changed" 
    console.log(defaultThing); // "initial" 
    console.log(anotherDefaultThing); // "initial" 
}, 1000);

按值传递,export default ... 后跟的东西被视为一个表达式,就好像它在导出之前被分配给一个隐藏变量

  • export {thing as default}
// module.js 
let thing = 'initial'; 
export { thing, thing as default }; 
setTimeout(() => { thing = 'changed'; }, 500);
// main.js 
import { thing, default as defaultThing } from './module.js'; 
import anotherDefaultThing from './module.js'; 

setTimeout(() => { 
    console.log(thing); // "changed" 
    console.log(defaultThing); // "changed" 
    console.log(anotherDefaultThing); // "changed" 
}, 1000);

始终按引用传递,因为我们无法直接通过export {}导出值,

  • 导出默认function
// module.js 
export default function thing() {} 
setTimeout(() => { thing = 'changed'; }, 500);
// main.js 
import thing from './module.js'; 
setTimeout(() => { 
    console.log(thing); // "changed" 
}, 1000);

export default function有自己的小脾气。在这种情况下,函数是通过引用传递的

  • module.js改一下
// module.js 
function thing() {} 
export default thing

setTimeout(() => { thing = 'changed'; }, 500);

此时,将是按值传递

  • 总结

image.png