Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript的深拷贝浅拷贝,深拷贝/比较 与 immutable 数据差异 #6

Open
yijinc opened this issue Jul 15, 2019 · 1 comment
Labels
blog blogs and articles

Comments

@yijinc
Copy link
Owner

yijinc commented Jul 15, 2019

JavaScript深拷贝浅拷贝

JavaScript 数据类型分为两种:

  • 基础类型:像Number、String、Boolean等
  • 引用类型:像Object、Array、Function等

浅拷贝只是复制了对象的引用地址,两个对象指向同一个内存地址,所以修改其中任意的值,另一个值都会随之变化。Array.prototype.slice/concatObject.assign 扩展运算符... 都是浅拷贝

var obj = { a: 1, b: { foo: 'foo' } };
var newObj = {...obj};  // 或 var newObj = Object.assign({}, obj);
newObj.b.foo = 0;
console.log(obj);   // { a: 1, b: { foo: 0 } };

与之对应的就是深拷贝,深拷贝就是指完全的拷贝一个对象,即使嵌套了对象,两者也相互分离,修改一个对象的属性,也不会影响另一个。

JSON.parse( JSON.stringify(obj) ) 可以简单粗暴的作为深拷贝,但不能拷贝函数

自己实现一个深拷贝

var deepCopy = function(obj) {
    if (typeof obj !== 'object') return;
    var newObj = obj instanceof Array ? [] : {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
        }
    }
    return newObj;
}

一般在开发中会引用第三方工具库,会提供深拷贝方法 如 lodash的_.cloneDeep, jquery的$.extend, immutable的数据转换等

@yijinc yijinc added the blog blogs and articles label Aug 20, 2021
@yijinc yijinc changed the title JavaScript的深拷贝浅拷贝 JavaScript的深拷贝浅拷贝,深拷贝/比较 与 immutable 数据差异 Jun 30, 2022
@yijinc
Copy link
Owner Author

yijinc commented Jun 30, 2022

深拷贝/比较 与 immutable 数据差异

我们在处理复杂 js 对象的时候,因为对象是引用类型,往往会因为修改了对象而产生副作用———因为不知道谁还引用着这份数据(或子属性数据),不知道这些修改会影响到谁。因此我们经常会把对象做一次深拷贝再放到处理函数中。
如果需要频繁地操作一个复杂对象,每次都完全深拷贝一次的话效率太低了,大部分场景下都只是更新了这个对象一两个字段,其他的字段都不变,对这些不变的字段的拷贝明显是多余的。

这时就出现了持久化数据immutable,在操作对象的时候只 clone 变化的节点和其祖先节点,其他的保持不变。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blog blogs and articles
Projects
None yet
Development

No branches or pull requests

1 participant