【JS】具名导入是解构吗

时间:2025-04-08 14:16:41

前言

下面两个js实现了暴露和导入功能

export let n = 1
export const increase = () => {
  n++
}
  • 1
  • 2
  • 3
  • 4

import { n, increase } from "./"
console.log(n, increase)
  • 1
  • 2

乍一看{ name, sayHello }写法和JS的解构写法一致,那么具名导入是解构吗,下文分析一下。

分析

尝试修改n

import { n, increase } from "./"

console.log(n) // 1
increase()
console.log(n) // 2
  • 1
  • 2
  • 3
  • 4
  • 5

模拟将导入方式变为JS解构

const obj = {
  n: 1,
  increase() {
    this.n++
  },
}
const { n, increase } = obj

console.log(n) // 1
increase()
console.log(n) // 1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

可以发现,二者打印结果并不一致,所以得出结论:具名导入并不是解构。

总结

解构全称解构赋值,是将值从对象中解构并赋值给新变量,新变量有自己的存储空间,所以对象中的变量即使变化了,也不会影响新变量,可以理解为新变量初始值只是解构那一瞬间对象中的值。

具名导入则不同,它并不会为变量开辟新空间,而只是引用了对象中的值,所以当对象发生改变时,该值也会随之改变。

所以具名导入并非解构赋值,需要区分二者。