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

深浅拷贝 #3

Open
JeromeYangtao opened this issue Nov 5, 2017 · 0 comments
Open

深浅拷贝 #3

JeromeYangtao opened this issue Nov 5, 2017 · 0 comments

Comments

@JeromeYangtao
Copy link
Owner

JeromeYangtao commented Nov 5, 2017

深浅拷贝介绍

常见的"深拷贝"方法

列举一些网络上常见博客提到的深拷贝方法,并总结一些它们的优缺点

Array.prototype.slice()和Array.prototype.concat()
var arr = ['wsscat', 'autumns', 'winds'];
var arrCopy = arr.slice(0);
arrCopy[0] = 'tacssw'
console.log(arr)//['wsscat', 'autumns', 'winds']
console.log(arrCopy)//['tacssw', 'autumns', 'winds']

优点:比较简单,不过不推荐使用。因为有bug更少且同样简单的方法
缺点:如果数组里面有 Object 的情况下深拷贝失败

JSON.stringify()和JSON.parse()

优点:使用简单,利用了JSON的特性
缺点:也是因为JSON的特性,不能实现对函数,undefined,symbol和不可枚举对象的深拷贝。抛弃对象的constructor,也就是深复制之后,无论这个对象原本的构造函数是什么,在深复制之后都会变成Object

Object.assign()

缺点:会跳过那些值为 null 或 undefined 的对象。Object.assign()拷贝的是属性值。假如源对象的属性值是一个指向对象的引用,它也只拷贝那个引用值

定义一个新的对象并遍历新的属性上去实现深拷贝

let obj = {
    name: 'wsscat',
    age: 0,
    run: function() {
        console.log('run')
    }
}

let obj2 = new Object();
obj2.name = obj.name;
obj2.age = obj.age
obj2.run = obj.run

obj.run = function() {
    console.log('run agail')
}

obj.run()
obj2.run()

这种深拷贝方法是比较好的一种,没有找出明显bug(不过深究起来的话,这其实也不是真正的深拷贝,因为构造函数和原型链不一样)

封装一个深拷贝方法

let obj = {
    name: 'wsscat',
    age: 0
}
let deepCopy = function(source) {
    let result = {};
    for (let key in source) {
        if (typeof source[key] === 'object') {
            result[key] = deepCopy(source[key])
        } else {
            result[key] = source[key]
        }
    }
    return result;
}
let obj3 = deepCopy(obj)
obj.name = 'autumns';
console.log(obj); //Object {name: "autumns", age: 0}
console.log(obj3); //Object {name: "wsscat", age: 0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant