admin管理员组

文章数量:1206196

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?

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?

Share Improve this question edited Oct 25, 2017 at 16:46 Avery235 asked Oct 25, 2017 at 16:23 Avery235Avery235 5,30616 gold badges56 silver badges87 bronze badges 3
  • 1 Also check this : stackoverflow.com/questions/32558514/… – GramThanos Commented Oct 25, 2017 at 16:29
  • export const x; looks invalid to me. – Felix Kling Commented Oct 25, 2017 at 16:33
  • 1 ES2015 modules export (live) bindings, not values. Read this Q&A about the differences between bindings and references. – user6445533 Commented Oct 25, 2017 at 16:34
Add a comment  | 

2 Answers 2

Reset to default 19

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

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

本文标签: javascriptES6 variable import by reference or copyStack Overflow