10

Suppose i have a var.js

export let x = 1;
export const f = () => x = 5;

Then i execute this in another file

import { x, f } from './var.js';
console.log(x); // 1
f();
console.log(x); // 5

Why is the imported variable x able to change accordingly?

Does import { x } gets re-evaluated when x in var.js changes?

Or is x a reference to the original x in var.js rather than a copy?

Avery235
  • 4,756
  • 12
  • 49
  • 83
  • 1
    Also check this : https://stackoverflow.com/questions/32558514/javascript-es6-export-const-vs-export-let – GramThanos Oct 25 '17 at 16:29
  • `export const x;` looks invalid to me. – Felix Kling Oct 25 '17 at 16:33
  • 1
    ES2015 modules export (live) bindings, not values. Read this [Q&A](https://stackoverflow.com/q/39259729) about the differences between bindings and references. –  Oct 25 '17 at 16:34

2 Answers2

15

ES6 import/exports are actually bindings (references). As the value of x in original file var.js changes, it's reflected in another file too.

Reference: http://2ality.com/2015/07/es6-module-exports.html

Theogry
  • 266
  • 2
  • 7
3

solution doesn't work for functions

export let e = () => {
  console.log('b')
}

window.b = () => {
  e = () => {
    console.log('c')
  }
}

the when calling from another file, the "reference" doesn't change.

import { e } from './test'
e() // b
b()
e() // still b
zavr
  • 2,049
  • 2
  • 18
  • 28