本文转自:http://blog.csdn.net/waiterwaiter/article/details/50267787

最近也一直会用javascript,然后中间使用的一些组件,如Echarts 会有非常复杂的配置文件,而大部分配置可能都是一样的,所以想着写一份通用配置,然后,其他地方需要使用的时候,用这份配置深拷贝一份配置,然后在上面继续改。就如下:

const defaultOpt = {
key1: xxx,
key2: {
dd: ee
},
.....
}; // deepCopy为某个实现深拷贝的方法
const opt1 = deepCopy(defaultOpt);
opt1.....
const opt2 = deepCopy(defaultOpt);
opt2.....
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

深拷贝和浅拷贝

这里也涉及到一个深拷贝和浅拷贝的概念。javascript中存储对象都是存地址的,所以浅拷贝是都指向同一块内存区块,而深拷贝则是另外开辟了一块区域。下面实例也可以看出这一点:

// 浅拷贝
const a = {t: 1, p: 'gg'};
const b = a;
b.t = 3;
console.log(a); // {t: 3, p: 'gg'}
console.log(b); // {t: 3, p: 'gg'} //深拷贝
const c = {t: 1, p: 'gg'};
const d = deepCopy(c);
d.t = 3;
console.log(c); // {t: 1, p: 'gg'}
console.log(d); // {t: 3, p: 'gg'}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

可以明显看出,浅拷贝在改变其中一个值时,会导致其他也一起改变,而深拷贝不会。

Object.assign()

我需要的是深拷贝的方法,然后发现原来es6 中有Object.assign() 这个方法,感觉可以拿来用了。 贴一下两个官方例子:

// Cloning an object
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
  • 1
  • 2
  • 3
  • 4
// Merging objects
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 }; var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

是不是很完美,又可以clone又可以merge。在我这种情况下,我觉得我的代码量又可以减少了,比如:

const defaultOpt = {
title: 'hello',
name: 'oo',
type: 'line'
};
// 原来可能需要这样
const opt1 = deepCopy(a);
opt1.title = 'opt1';
opt1.type = 'bar';
opt1.extra = 'extra'; // 额外增加配置
// 现在只要这样
const opt2 = Object.assign({}, a, {
title: 'opt2',
type: 'bar',
extra: 'extra'
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

不过,很快,问题出现了,那就是

merge和我想象的不一样

且看例子:

const defaultOpt = {
title: {
text: 'hello world',
subtext: 'It\'s my world.'
}
}; const opt = Object.assign({}, defaultOpt, {
title: {
subtext: 'Yes, your world.'
}
}); console.log(opt); // 预期结果
{
title: {
text: 'hello world',
subtext: 'Yes, your world.'
}
}
// 实际结果
{
title: {
subtext: 'Yes, your world.'
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

原本想的是它只会覆盖subtext ,然而其实它直接覆盖了整个title ,这个让我比较郁闷,相当于它只merge根属性,下面的就不做处理了。 代码只能重构成相对麻烦一点的:

const defaultOpt = {
title: {
text: 'hello world',
subtext: 'It\'s my world.'
}
}; const opt = Object.assign({}, defaultOpt);
opt.title.subtext = 'Yes, your world.'; console.log(opt);
// 结果正常
{
title: {
text: 'hello world',
subtext: 'Yes, your world.'
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

这样用虽然麻烦一点,但是也还好,可以用了。不过。。。很快,又出现问题了,如下:

const defaultOpt = {
title: {
text: 'hello world',
subtext: 'It\'s my world.'
}
}; const opt1 = Object.assign({}, defaultOpt);
const opt2 = Object.assign({}, defaultOpt);
opt2.title.subtext = 'Yes, your world.'; console.log('opt1:');
console.log(opt1);
console.log('opt2:');
console.log(opt2); // 结果
opt1:
{
title: {
text: 'hello world',
subtext: 'Yes, your world.'
}
}
opt2:
{
title: {
text: 'hello world',
subtext: 'Yes, your world.'
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

上面结果发现两个配置变得一模一样,而其实我们并没有去更改opt1subtext ,只是改了opt2 的。 这说明一点:在title 这一层只是简单的浅拷贝 ,而没有继续深入的深拷贝。 这里不经让我怀疑这个接口到底是怎么实现的,它到底是不是和我所想的一样。 翻了一下官方文档,发现它写得一个Polyfill ,代码我加了点注释如下:

if (!Object.assign) {
// 定义assign方法
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) { // assign方法的第一个参数
'use strict';
// 第一个参数为空,则抛错
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
} var to = Object(target);
// 遍历剩余所有参数
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
// 参数为空,则跳过,继续下一个
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource); // 获取改参数的所有key值,并遍历
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
// 如果不为空且可枚举,则直接浅拷贝赋值
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

上面的代码可以直接说明它只对顶层属性做了赋值,完全没有继续做递归之类的把所有下一层的属性做深拷贝。

总结

Object.assign() 只是一级属性复制,比浅拷贝多深拷贝了一层而已。用的时候,还是要注意这个问题的。

发现一个可以简单实现深拷贝的方法,当然,有一定限制,如下:

const obj1 = JSON.parse(JSON.stringify(obj));
  • 1

思路就是将一个对象转成json字符串,然后又将字符串转回对象。

本文转自:http://blog.csdn.net/waiterwaiter/article/details/50267787

[转]javascript之Object.assign()痛点的更多相关文章

  1. javascript系列--Object.assign实现浅拷贝的原理以及实现

    一.前言 之前在前面一篇学习了赋值,浅拷贝和深拷贝.介绍了这三者的相关知识和区别. 传送门:https://www.mwcxs.top/page/592.html 本文会介绍浅拷贝Object.ass ...

  2. es6 javascript对象方法Object.assign()

    es6 javascript对象方法Object.assign() 2016年12月01日 16:42:34 阅读数:38583 1  基本用法 Object.assign方法用于对象的合并,将源对象 ...

  3. JavaScript 复制对象【Object.assign方法无法实现深复制】

    在JavaScript这门语言中,数据类型分为两大类:基本数据类型和复杂数据类型.基本数据类型包括Number.Boolean.String.Null.String.Symbol(ES6 新增),而复 ...

  4. javascript学习总结之Object.assign()方法详解

    最近再写ES6的文章时候发现自己对Object.assign()方法不太了解,之前也没有接触过所以就就查阅了相关的资料,为了自己以后肯能会用到以及对知识进行巩固,所以在这里记录下自己学习的点点滴滴,毕 ...

  5. [Javascript] Object.assign()

    Best Pratices for Object.assign: http://www.cnblogs.com/Answer1215/p/5096746.html Object.assign() ca ...

  6. es6 javascript对象方法Object.assign() 对象的合并复制等

    Object.assign方法用于对象的合并,将源对象( source )的所有可枚举属性,复制到目标对象( target ). 详细使用稳步到前辈: http://blog.csdn.net/qq_ ...

  7. ecma 2018, javascript spread syntax behaves like Object.assign

    as the subject. It is only supported in Chrome version 60+, so, first check the version, or just use ...

  8. [Javascript] Combine Objects with Object.assign and Lodash merge

    Learn how to use Object.assign to combine multiple objects together. This pattern is helpful when wr ...

  9. 微信不支持Object.assign

    微信不支持Object.assign,让我Vue怎么用QAQ... 解决方法: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Refe ...

随机推荐

  1. python中list的sort方法

    转:https://www.cnblogs.com/zle1992/p/6271105.html 使用python对列表(list)进行排序,说简单也简单,说复杂也复杂,我一开始学的时候也搞不懂在说什 ...

  2. ASP.NET MVC URL重写与优化(初级篇)-使用Global路由表定制URL

    ASP.NET MVC URL重写与优化(初级篇)-使用Global路由表定制URL 引言--- 在现今搜索引擎制霸天下的时代,我们不得不做一些东西来讨好爬虫,进而提示网站的排名来博得一个看得过去的流 ...

  3. C#DataGridView的简单使用

    首先创建一个DataGridView控件,然后创建列(包括列名的定义), 由于我不是和数据库进行连接,只是为了输出好看一点. 删除所有数据: while (this.dataGridView1.Row ...

  4. 【文文殿下】Win7打开无线热点

    下载程序 : https://files.cnblogs.com/files/Syameimaru/wifi.rar 打开config.ini 修改相关信息,然后运行程序. 运行成功后,打开网络和共享 ...

  5. jzoj5875

    這玩意嚴格意義上算是水法(因為可能會被卡) 題目中,如果按照一般的bfs來搜索,那麼有平方級邊,會tle 如果按照補邊的線性來搜索,那麼時間複雜度變為min(k*k,m)*n,視n,m同階,則時間複雜 ...

  6. Aizu 2249Road Construction 单源最短路变形《挑战程序设计竞赛》模板题

    King Mercer is the king of ACM kingdom. There are one capital and some cities in his kingdom. Amazin ...

  7. tenda某路由器信息泄露查找

    本文作者:i春秋作家——icqb32d3a26 1: 前期准备: (1) 路由器固件 一般获取固件的方法有以下几种 官方网站根据对应版本下载(√),点击下载 在点击更新固件时抓取对应的更新固件链接 拆 ...

  8. PHP 5.6 如何使用 CURL 上传文件

    以前我们通过 PHP 的 cURL 上传文件是,是使用“@+文件全路径”的来实现的: curl_setopt(ch, CURLOPT_POSTFIELDS, array( 'file' => ' ...

  9. elasticsearch Geo Bounding Box Query

    Geo Bounding Box Query 一种查询,允许根据一个点位置过滤命中,使用一个边界框.假设以下索引文档: PUT /my_locations { "mappings" ...

  10. 用switch函数根据选择不同的radio出现不同的视图

    html代码: <!DOCTYPE html> <html> <head> <title></title> <style type=& ...