我想知道解构时ES6模块的导出绑定是如何工作的。我正在导出一个对象(thing)作为一个命名的导出--但也是它的一个属性(foo),稍后我将对其进行更新。
当我导入对象并引用它的支柱时,这个更新是有效的,但是当我直接导入foo时就不行了,如下所示。我猜export const...创建了一个新的、不可变的绑定,但是在导出时有什么方法可以保留对原始对象的引用呢?
// module: 'thing.js'
let thing = {
foo: (x) => console.log(x)
};
const init = () => {
thing.foo = (x) => console.log("updated");
};
export { init, thing };
export const { foo } = thing;// index.js
import { foo, thing, init } from "./thing";
init();
foo("test"); // does not work
thing.foo("test"); // update is reflected, here发布于 2022-08-23 16:20:10
出口/进口没有问题。
参见此示例:
let thing = {
foo: (x) => console.log(x)
};
const init = () => {
thing.foo = (x) => console.log("updated");
};
const foo = thing.foo;
init();
foo("test"); //test
thing.foo("test"); //updated变量foo和字段thing.foo在init函数中重写thing.foo后包含不同的函数。
https://stackoverflow.com/questions/73461362
复制相似问题