为什么我的闭包中函数的效果不持久?

Why are the effects of a function inside my closure not persisting?

我有以下代码(为简洁起见进行了编辑)。当我从 Node 的实例调用 addAttribute 时,attributes 映射在 attributes 函数 中正确更新 ,但是当代码步出该函数,更新丢失。

鉴于 attributes 已关闭,我希望不会发生这种情况。关于为什么的任何想法?如有任何建议,我们将不胜感激!

const Node = function(nodeData) {
  let attributes = new Map();

  const addAttribute = function (attribute) {
    attributes = new Map([...attributes, ...attribute]);
    console.log(attributes); // Works correctly, as expected.
  }

  console.log(attributes); // Shows empty map, decidedly not as expected.

  return {
    attributes,
    addAttribute,
  }
}

当你调用 Node 时,它 returns 一个带有 attributes 属性 的对象。 属性 保存值 attributes 变量的副本(这是一个空映射)。

稍后您调用 addAttribute,它会用另一个新映射覆盖 attributes 变量。

这不会更改之前分配给 attributes 属性 的原始地图。


记住:attributes 属性 保存了 attributes 变量原始值的副本。它持有对变量的引用。


如果要更新返回的地图,则需要改变现有地图,而不是替换 attributes 变量的值。

例如attributes.set( attribute[0], attribute[1] )


为了简化,没有闭包:

{

  const original = new Map([
    [1, "one"],
    [2, "two"]
  ]);
  const other = new Map([...original, [3, "three"]]);
  console.log("original is unchanged", [...original.values()]);

};

{

  const original = new Map([
    [1, "one"],
    [2, "two"]
  ]);
  original.set(3, "three");
  console.log("original is mutated", [...original.values()]);

}