简体   繁体   English

ES6 变量通过引用或复制导入

[英]ES6 variable import by reference or copy

Suppose i have a var.js假设我有一个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?为什么导入的变量x能够相应地改变?

Does import { x } gets re-evaluated when x in var.js changes?var.js x更改时,会重新评估import { x }吗?

Or is x a reference to the original x in var.js rather than a copy?或者x是对var.js原始xvar.js而不是副本?

ES6 import/exports are actually bindings (references). ES6 导入/导出实际上是绑定(引用)。 As the value of x in original file var.js changes, it's reflected in another file too.随着原始文件var.jsx的值发生变化,它也会反映到另一个文件中。

Reference: http://2ality.com/2015/07/es6-module-exports.html参考: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM