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?
2 Answers
Reset to default 19ES6 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
版权声明:本文标题:javascript - ES6 variable import by reference or copy - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738720015a2108689.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
export const x;
looks invalid to me. – Felix Kling Commented Oct 25, 2017 at 16:33