JS:Object.assign()是否创建深拷贝或浅拷贝 [英] JS: Does Object.assign() create deep copy or shallow copy

查看:1091
本文介绍了JS:Object.assign()是否创建深拷贝或浅拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚遇到这个概念

var copy = Object.assign({}, originalObject);

将原始对象的副本创建到副本对象。但是,我的问题是,这种克隆对象的方式是创建深拷贝还是浅拷贝?

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.

推荐答案

忘记深拷贝,即使浅拷贝也不安全,如果您要复制的对象具有枚举的属性属性设置为false。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆