为什么我计算的 属性 在 Object.assign 之后无效?

Why is my computed property not effective after Object.assign?

我在现代 JavaScript:

中偶然发现了与此类似的代码

let obj = {
  data: {number: 9},
  set prop(p) {
    this.data = p;
  },
  get prop() {
    return this.data;
  }
};

obj = Object.assign({}, obj, {
  data: {number: 2}
});

console.log('obj.data === obj.prop ', obj.data === obj.prop);
console.log('obj.data.number === obj.prop.number ', obj.data.number === obj.prop.number);

任何修改都在计算的 属性 之外进行,就好像有 none.

我原以为计算出的 属性 仍然存在。

有没有办法在调用 Object.assign 后保留计算的 属性?谢谢

考虑以下几点:

let ex = {
  o: 1
}

let ex2 = {
  o: 1
}

console.log(ex === ex2);

相同的对象不能等同。

如果您查看 object.assign 创建的新对象的结果,您会发现它不再具有 getter/setter,而是具有 属性 propobject.assign 不会复制 getter/setter 函数,而是调用 [[get]] 并创建一个新的 属性。

MDN describes it:

It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

因此 assign() 将具有 prop 属性 的对象与具有 data 属性 的对象合并,您将同时获得:

let obj = {
  data: {
    number: 9
  },

  set prop(p) {
    this.data = p;
  },

  get prop() {
    return this.data;
  }

};

obj = Object.assign({}, obj, {
  data: {
    number: 2
  }
});

// it has a data and a prop property -- they are not the same:
console.log(obj)