通过structuredClone()接收的对象副本与原始对象不相等。

huangapple go评论64阅读模式
英文:

The object copy received via structuredClone() is not equal to the original

问题

我尝试使用 structuredClone() 创建对象的副本,然后将其与原始对象进行比较。

const util = require('util');

function A() {}
let obj = {
    key: new A()
};
let copy = structuredClone(obj);
console.log(util.isDeepStrictEqual(obj, copy));

我期望的结果是 true,但收到的是 false

你能解释原因吗?

英文:

I try creating a copy of an object with structuredClone() and then compare it to the original.

const util = require('util');

function A() {}
let obj = {
    key: new A()
};
let copy = structuredClone(obj);
console.log(util.isDeepStrictEqual(obj, copy));

I expect true, but received false.

Could you explain the reason?

答案1

得分: 2

原因是 structuredClone 无法克隆类或函数,所以你的 A {} 在克隆对象中变成了 {}

示例:

const util = require('util');

function A() { this.property = 8 }
let obj = {
    key: new A()
};

let copy = structuredClone(obj);
console.log("Obj is:", obj)
console.log("Copy is:", copy)

显示结果为:

Obj is: { key: A { property: 8 } }
Copy is: { key: { property: 8 } }

如你所见,副本不再是 A 的实例,而是一个普通的 JavaScript 对象。

英文:

The reason is structuredClone cannot clone classes or functions, so your A {} becomes {} in the cloned object.

Example:

const util = require('util');

function A(){ this.property = 8}
let obj = {
    key: new A()
};

let copy = structuredClone(obj);
console.log("Obj is:", obj)
console.log("Copy is:", copy)

That shows:

Obj is: { key: A { property: 8 } }
Copy is: { key: { property: 8 } }

As you can see, the copy is no more an A instance... is a Plain Javascript Object

huangapple
  • 本文由 发表于 2023年7月13日 21:00:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定