JS:Object.assign() 创建深拷贝还是浅拷贝 [英] JS: Does Object.assign() create deep copy or shallow copy
问题描述
我刚接触到这个概念
var copy = Object.assign({}, originalObject);
将原始对象的副本创建到copy
"对象中.但是,我的问题是,这种克隆对象的方式是创建深拷贝还是浅拷贝?
which creates a copy of original object into the "copy
" object. However, my question is, does this way of cloning object create a deep copy or a shallow copy?
PS:令人困惑的是,如果它创建了一个深拷贝,那么这将是克隆对象的最简单方法.
PS: The confusion is, if it creates a deep copy, then it would be the easiest way to clone an object.
推荐答案
忘记深拷贝,即使是浅拷贝也不安全,如果你正在拷贝的对象有一个带有 enumerable
属性的属性设置为假.
Forget about deep copy, even shallow copy isn't safe, if the object you're copying has a property with enumerable
attribute set to false.
MDN:
Object.assign() 方法只复制可枚举的和自己的属性从源对象到目标对象
The Object.assign() method only copies enumerable and own properties from a source object to a target object
举个例子
var o = {};
Object.defineProperty(o,'x',{enumerable: false,value : 15});
var ob={};
Object.assign(ob,o);
console.log(o.x); // 15
console.log(ob.x); // undefined
这篇关于JS:Object.assign() 创建深拷贝还是浅拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!