英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论