Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 variable import by reference or copy

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?

like image 680
Avery235 Avatar asked Oct 25 '17 16:10

Avery235


2 Answers

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

like image 108
Theogry Avatar answered Oct 25 '22 17:10

Theogry


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
like image 45
zavr Avatar answered Oct 25 '22 16:10

zavr